module:{ rules:[ { test:/\.js$/, use:['babel-loader?cacheDirectory'], include:path.resolve(__dirname,'src'), exclude:/node_modules/ } ] }
resolve: { modules: [path.resolve(__dirname, 'node_modules')] },
mainFields
用于配置第三方模块使用那个入口文件 isomorphic-fetch
resolve.alias
配置项经过别名来把原导入路径映射成一个新的导入路径 此优化方法会影响使用Tree-Shaking
去除无效代码
alias: { 'react': path.resolve(__dirname, './node_modules/react/cjs/eact.production.min.js') }
extensions: ['.js', '.json']
resolve: { extensions: ['js'] },
module: { noParse: [/react\.min\.js/] }
被忽略掉的文件里不该该包含 import 、 require 、 define 等模块化语句css
module.exports = { entry: { react: ['react'] //react模块打包到一个动态链接库 }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].dll.js', //输出动态链接库的文件名称 library: '_dll_[name]' //全局变量名称 }, plugins: [ new webpack.DllPlugin({ name: '_dll_[name]', //和output.library中一致,值就是输出的manifest.json中的 name值 path: path.join(__dirname, 'dist', '[name].manifest.json') }) ] }
webpack --config webpack.dll.config.js --mode production
plugins: [ new webpack.DllReferencePlugin({ manifest: require(path.join(__dirname, 'dist', 'react.manifest.json')), }) ],
webpack --config webpack.config.js --mode development
npm i happypack@next -D
module: { rules: [{ test: /\.js$/, //把对.js文件的处理转交给id为babel的HappyPack实例 use: 'happypack/loader?id=babel', include: path.resolve(__dirname, 'src'), exclude: /node_modules/ }, { //把对.css文件的处理转交给id为css的HappyPack实例 test: /\.css$/, use: 'happypack/loader?id=css', include: path.resolve(__dirname, 'src') }], noParse: [/react\.min\.js/] },
plugins: [ //用惟一的标识符id来表明当前的HappyPack是用来处理一类特定文件 new HappyPack({ id: 'babel', //如何处理.js文件,和rules里的配置相同 loaders: [{ loader: 'babel-loader', query: { presets: [ "env", "react" ] } }] }), new HappyPack({ id: 'css', loaders: ['style-loader', 'css-loader'], threads: 4, //表明开启几个子进程去处理这一类型的文件 verbose: true //是否容许输出日子 }) ],
ParallelUglifyPlugin
能够把对JS文件的串行压缩变为开启多个子进程并行执行
npm i -D webpack-parallel-uglify-plugin
new ParallelUglifyPlugin({ workerCount: 3, //开启几个子进程去并发的执行压缩。默认是当前运行电脑的 CPU 核数减去1 uglifyJS: { output: { beautify: false, //不须要格式化 comments: false, //不保留注释 }, compress: { warnings: false, // 在UglifyJs删除没有用到的代码时不输出警告 drop_console: true, // 删除全部的 `console` 语句,能够兼容ie浏览器 collapse_vars: true, // 内嵌定义了可是只用到一次的变量 reduce_vars: true, // 提取出出现屡次可是没有定义成变量去引用的静态值 } }, })
watch: true, //只有在开启监听模式时,watchOptions才有意义 watchOptions: { ignored: /node_modules/, aggregateTimeout: 300, //监听到变化发生后等300ms再去执行动做,防止文件更新太快致使编译频率过高 poll: 1000 //经过不停的询问文件是否改变来判断文件是否发生变化,默认每秒询问1000次 }
aggregateTimeout
配置devServer: { contentBase: './dist', inline: true },
webpack负责监听文件变化,webpack-dev-server负责刷新浏览器 这些文件会被打包到chunk中,它们会代理客户端向服务器发起WebSocket链接node
(webpack)-dev-server/client/overlay.js 3.58 KiB {0} [built] (webpack)-dev-server/client/socket.js 1.05 KiB {0} [built] ./node_modules/loglevel/lib/loglevel.js 7.68 KiB {0} [built] ./node_modules/strip-ansi/index.js 161 bytes {0} [built] ./node_modules/url/url.js 22.8 KiB {0} [built] (webpack)-dev-server/client?http://localhost:8080 7.75 KiB {0} [built] multi (webpack)-dev-server/client?http://localhost:8080 ./src/index.js 40 bytes {0} [built]
devServer: { hot:true }
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[0] multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/index.js 52 bytes {main} [built]
[./node_modules/webpack/hot/dev-server.js] (webpack)/hot/dev-server.js 1.66 KiB {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 77 bytes {main} [built]
if (module.hot) { module.hot.accept('./index.js', function () { console.log('accept index.js'); }); }
优化模块热替换浏览器日志react
plugins: [ new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin(), ]
在开发网页的时候,通常都会有多套运行环境,例如:webpack
if(process.env.NODE_ENV == 'production'){ console.log('生产环境'); }else{ console.log('开发环境'); }
当你使用process模块的时候,webpack会把process模块打包进来git
new webpack.DefinePlugin({ 'process.env': { NODE_ENV:JSON.stringify('production') } }),
定义环境变量的值时用 JSON.stringify 包裹字符串的缘由是环境变量的值须要是一个由双引号包裹的字符串,而 JSON.stringify('production')的值正好等于'"production"'github
new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), })
output: { path: path.resolve(__dirname, 'dist'), filename: '[name]_[hash:8].js', publicPath: 'http://img.zhufengpeixun.cn' },
Tree Shaking
能够用来剔除JavaScript
中用不上的死代码。它依赖静态的ES6
模块化语法,例如经过import
和export
导入导出。{ loader: 'babel-loader', query: { presets: [ [ "env", { modules: false //含义是关闭 Babel 的模块转换功能,保留本来的 ES6 模块化语法 } ], "react" ] } }
webpack --display-used-exports
const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); plugins: [ new UglifyJSPlugin() ]
webpack --display-used-exports --optimize-minimize
webpack --mode production
entry: { pageA: './src/pageA', pageB: './src/pageB' }, optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minChunks: 2, maxInitialRequests: 5, // The default limit is too small to showcase the effect minSize: 0 // This is example is too small to create commons chunks }, vendor: { test: /node_modules/, chunks: "initial", name: "vendor", priority: 10, enforce: true } } } },
export default 'Hello';
import str from './hello.js';
console.log(str);
var util = ('Hello'); console.log(util);
函数由两个变成了一个,hello.js 中定义的内容被直接注入到了 main.js 中web
const ModuleConcatenationPlugin = require('webpack/lib/optimize/ModuleConcatenationPlugin'); module.exports = { resolve: { // 针对 Npm 中的第三方模块优先采用 jsnext:main 中指向的 ES6 模块化语法的文件 mainFields: ['jsnext:main', 'browser', 'main'] }, plugins: [ // 开启 Scope Hoisting new ModuleConcatenationPlugin(), ], };
--display-optimization-bailout
entry: { index: './src/index.js', another: './src/another-module.js' }
optimization: { splitChunks: { cacheGroups: { commons: { chunks: "initial", minChunks: 2 }, vendor: { test: /node_modules/, chunks: "initial", name: "vendor", } }
document .getElementById('clickMe') .addEventListener('click', () => { import (/*webpackChunkName:"alert"*/ './alert').then(alert => { console.log(alert); alert.default('hello'); }); });
loaders: [ { loader: 'babel-loader', query: { presets: ["env", "stage-0", "react"] } } ]
const path = require("path") const express = require("express") const webpack = require("webpack") const webpackDevMiddleware = require("webpack-dev-middleware") const webpackConfig = require('./webpack.config.js') const app = express(), DIST_DIR = path.join(__dirname, "dist"),// 设置静态访问文件路径 PORT = 9090, // 设置启动端口 complier = webpack(webpackConfig) app.use(webpackDevMiddleware(complier, { //绑定中间件的公共路径,与webpack配置的路径相同 publicPath: webpackConfig.output.publicPath, quiet: true //向控制台显示内容 })) // 这个方法和下边注释的方法做用同样,就是设置访问静态文件的路径 app.use(express.static(DIST_DIR)) app.listen(PORT,function(){ console.log("成功启动:localhost:"+ PORT) })
webpack --profile --json > stats.json
Webpack 官方提供了一个可视化分析工具 Webpack Analyseexpress
当用 Webpack 去构建一个能够被其余模块导入使用的库时须要用到它们。 npm
output.libraryTarget 是字符串的枚举类型,支持如下配置。 json
编写的库将经过 var 被赋值给经过 library 指定名称的变量。
假如配置了 output.library='LibraryName',则输出和使用的代码以下:
// Webpack 输出的代码 var LibraryName = lib_code; // 使用库的方法 LibraryName.doSomething(); 假如 output.library 为空,则将直接输出:
lib_code 其中 lib_code 代指导出库的代码内容,是有返回值的一个自执行函数。
编写的库将经过 CommonJS 规范导出。
假如配置了 output.library='LibraryName',则输出和使用的代码以下:
// Webpack 输出的代码 exports['LibraryName'] = lib_code; // 使用库的方法 require('library-name-in-npm')['LibraryName'].doSomething(); 其中 library-name-in-npm 是指模块发布到 Npm 代码仓库时的名称。
编写的库将经过 CommonJS2 规范导出,输出和使用的代码以下:
// Webpack 输出的代码 module.exports = lib_code; // 使用库的方法 require('library-name-in-npm').doSomething(); CommonJS2 和 CommonJS 规范很类似,差异在于 CommonJS 只能用 exports 导出,而 CommonJS2 在 CommonJS 的基础上增长了 module.exports 的导出方式。 在 output.libraryTarget 为 commonjs2 时,配置 output.library 将没有意义。
编写的库将经过 this 被赋值给经过 library 指定的名称,输出和使用的代码以下:
// Webpack 输出的代码 this['LibraryName'] = lib_code; // 使用库的方法 this.LibraryName.doSomething();
编写的库将经过 window 被赋值给经过 library 指定的名称,即把库挂载到 window 上,输出和使用的代码以下:
// Webpack 输出的代码 window['LibraryName'] = lib_code; // 使用库的方法 window.LibraryName.doSomething();
global
编写的库将经过 global 被赋值给经过 library 指定的名称,即把库挂载到 global 上,输出和使用的代码以下: // Webpack 输出的代码 global['LibraryName'] = lib_code; // 使用库的方法 global.LibraryName.doSomething();