引言
项目中经常用到共用的js,这里就需要用到共用js打包,这篇文章讲解两种打包方式,webpack打包和rollup打包两种方式
1、webpack打包js
1.1 在根目录创建 webpack.config.js,配置如下
const path = require('path');
module.exports = {entry: './index.js', output:{filename:'index.js',path:path.resolve(__dirname,'dist'),library: 'myModule',libraryTarget:'umd'},// 以下代码为新添加代码module:{rules:[{test: /\.js$/, // 匹配所有 js 文件loader: 'babel-loader' // 使用 babel-loader 处理 js 文件},]},
};
1.2 安装依赖包 package.json
npm install @babel/core @babel/preset-env babel-loader @babel/plugin-transform-runtime 这里用来将es6转成es5
npm install webpack webpack-cli
{"main": "index.js","scripts": {"buildwebpack": "webpack"},"devDependencies": {"@babel/core": "^7.23.9","@babel/preset-env": "^7.23.9","babel-loader": "^9.1.3","webpack": "^5.90.0","webpack-cli": "^5.1.4"},"dependencies": {"@babel/plugin-transform-runtime": "^7.23.9"}
}
1.3 配置 babel.config.js
const presets = [["@babel/env",{targets: {ie: "6",edge: "17",firefox: "60",chrome: "67",safari: "11.1"},//useBuiltIns: "usage",//corejs: "3", // <--- 此处加个这个,就没有报错警告了},],
];module.exports = { presets,"plugins": ["@babel/transform-runtime"]
};
1.4 webpack 支持vue
“vue-loader”: “^15.11.1”,
“vue-template-compiler”: “^2.6.12” //需要和vue版本一致
npm install vue-loader@15 vue-template-compiler@2 vue@2 css-loader
const path = require('path');
const {VueLoaderPlugin} = require('vue-loader')
module.exports = {entry: './index.js', output:{filename:'index.js',path:path.resolve(__dirname,'dist'),library: 'myModule',libraryTarget:'umd'},// 以下代码为新添加代码module:{rules:[{test: /\.js$/, // 匹配所有 js 文件loader: 'babel-loader' // 使用 babel-loader 处理 js 文件},{test: /\.vue$/, loader: 'vue-loader'},
// { test: /\.css$/,
// use: ['style-loader','css-loader' ]
// },]},//需要注意的点:vue-loader 15版本需加入插件plugins: [new VueLoaderPlugin()]
};
2、rollup 打包js
2.1 在根目录创建 rollup.config.js,配置如下
import babel from 'rollup-plugin-babel';
export default {input: 'index.js',output: {file: 'lib/index.js',format: 'cjs',},plugins: [ babel({runtimeHelpers: true, presets: ["@babel/preset-env"],}) ],
};
2.2 安装依赖包 package.json
npm install @babel/core @babel/preset-env 这里用来将es6转成es5
npm install rollup rollup-plugin-babel
{"main": "index.js","scripts": {"buildrollup": "rollup -c",},"devDependencies": {"@babel/core": "^7.23.9","@babel/preset-env": "^7.23.9","babel-loader": "^9.1.3"},"dependencies": {"@babel/plugin-transform-runtime": "^7.23.9","rollup": "^2.79.1","rollup-plugin-babel": "^4.4.0"}
}
2.4 rollup 打包vue
rollup-plugin-vue^5.1.9 + vue-template-compiler
rollup-plugin-postcss 识别css和预处理文件
npm install rollup-plugin-vue@5 vue-template-compiler rollup-plugin-postcss
export default {input: 'index.js',output: {file: 'lib/index.js',format: 'cjs',},plugins: [ babel({runtimeHelpers: true, presets: ["@babel/preset-env"],}),vue2({css:true,compilerTemplate: true,preprocessStyles: true}) ],
};