webpack学习
核心思想:一切皆模块;按需加载
一.webpack 打包过程
1.从入口文件开始分析应用的依赖树
2.将每个依赖模块包装起来放到一个数组中等待调用
3.把执行入口文件的逻辑放到一个立即执行函数中执行
二.loader 与 plugin
1.loader
loader是文件加载器,能够加载资源文件,并对这些文件进行编译、处理,最终一起打包到指定的文件中(比如.vue,.jsx.css文件。比如装换ES6到ES5)
2.plugin
plugin是扩展器,它是基于事件机制工作,会监听webpack打包过程中的某些事件节点,执行任务(比如打包完成后压缩代码,比如热更新)
三.webpack性能优化
1.打包结果优化(空间)
①减少打包体积,去除无用代码 ②代码压缩
2.构建过程优化(时间)
①happypack多进程处理文件 ②进行增量构建,缓存处理过的文件
四.我的webpack配置
1 const path = require('path') 2 const webpack = require('webpack') 3 const uglifyjs = require('uglifyjs-webpack-plugin') 4 const HtmlWebpackPlugin = require('html-webpack-plugin') 5 const TerserPlugin = require('terser-webpack-plugin') 6 const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin 7 const HappyPack = require('happypack'); 8 const os = require('os'); 9 //根据cpu数量创建线程池 10 const happyThreadPool = HappyPack.ThreadPool({ 11 size: os.cpus().length 12 }); 13 14 15 module.exports = { 16 optimization: { 17 minimizer: [new TerserPlugin({ 18 //加快构建速度 19 cache: true, 20 terserOptions: { 21 compress: { 22 unused: true, 23 drop_debugger: true, 24 drop_console: true, 25 dead_code: true 26 } 27 } 28 })] 29 }, 30 entry: './src/index.js', // 入口文件 31 output: { 32 path: path.join(__dirname, 'dist'), // 打包后文件放入的文件夹 33 filename: 'bundle.js' 34 }, 35 devServer: { 36 port: 3001, 37 publicPath: '/dist', 38 open: false, 39 hot: true, 40 // contentBase: 'dist' //指定打开浏览器显示的目录,默认为根目录(项目目录) 41 }, 42 resolve: { // 不写后缀的文件 43 extensions: ['.jsx', '.js', '.json'] 44 }, 45 module: { 46 rules: [{ 47 test: /\.css$/, 48 use: [ 49 'babel-loader', 50 'style-loader', 51 'css-loader' 52 ] 53 }, 54 { 55 test: /\.jsx?/, 56 exclude: /node_modules/, 57 use: [ 58 { 59 loader: 'happypack/loader?id=jsx', 60 }, 61 { 62 loader: 'babel-loader', 63 options: { 64 babelrc: false, 65 presets: [ 66 require.resolve('@babel/preset-react'), 67 require.resolve('@babel/preset-env', { 68 modules: false 69 }) 70 ] 71 } 72 } 73 ] 74 } 75 ] 76 }, 77 plugins: [ 78 new uglifyjs(), 79 new HtmlWebpackPlugin({ 80 template: path.resolve(__dirname, 'src/index.html'), 81 filename: 'index.html' 82 }), 83 new webpack.HotModuleReplacementPlugin(), 84 new BundleAnalyzerPlugin(), 85 new HappyPack({ 86 id: 'jsx', 87 threadPool: happyThreadPool, 88 loaders: ['babel-loader'] 89 }) 90 ], 91 // mode: 'production', 92 }
浙公网安备 33010602011771号