1、 伸手党css
webpack4基本配置html
2、具体变化
1.webpack4 并引入了mode概念,为开发,及生产环境提供两种不一样的默认配置,极大的简化了webpack的配置。
在4.0版本中,你甚至不须要配置,便可使用(虽然没什么用)。node
默认值webpack
module.exports = { entry: 'src/', outpu: { filename: '[name].js', path: 'dist/' } }
webpack 4中引入的mode是必需设置的(若是没有设置,会报警),你能够经过webpack --mode ...来设置,也能够经过webpack.config.js来设置。git
module.exports = { mode: 'development' // development || production }
mode也是为了简化配置项,不一样的mode会为咱们设置不一样的默认配置,就不须要咱们一个个去分别配置了。github
开发模式更关注开发体验:web
生成模式更关注用户体验:浏览器
性能(文件大小,运行性能,打包速度)详细性能描述参考缓存
3.pluginapp
(1) extract-text-webpack-plugin@4.0.0-beta.0
issue list 能够看到,问题仍是比较多的。
官方出了一个mini-css-extract-plugin,可是这个问题更多,不支持HMR,不支持contenthash,因此目前基本无法用。
(2)html-webpack-plugin@3.0.0+
这个插件目前是支持webpack 4的,只是他本身的插件不必定支持,这个在升级的时候须要注意
(3)uglifyjs-webpack-plugin
这个插件目前也是支持webpack 4的。其实在production模式下,代码是默认会压缩的。固然,若是你有更细致的自定义需求,就能够用到这个插件。
(4) CommonsChunkPlugin
上面讲到的都是一些第三方的插件改动,而改动最大,影响也最大的就是webpack 4使用optimization.splitChunks替代了CommonsChunkPlugin,而且支持移除了CommonsChunkPlugin,因此这部分迁移起来比较麻烦。
对于各位配置工程师来讲,CommonsChunkPlugin应该是很熟悉了,咱们主要用他来抽取代码中的共用部分,webpack runtime之类的代码,结合chunkhash,实现最好的缓存策略。而这一部分,也是webpack支持的比较差的,这个几乎三岁的issue,至今尚未解决。对这个问题比较感兴趣的,能够拜读一下这篇 文章。我这里就不展开了,直接贴一份CommonsChunkPlugin时代解决这个问题的配置
module.exports = { ... plugins: [ ... new webpack.HashedModuleIdsPlugin(), new webpack.NamedChunksPlugin(chunk => { if (chunk.name) { return chunk.name } else { return 'faceless-chunk' // a chunk has no name } }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks (module) { return ( module.resource && /\.js$/.test(module.resource) && /node_modules/.test(module.resource) ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'runtime', minChunks: Infinity }), // extracts shared chunks from code splitted chunks // https://github.com/webpack/webpack/issues/4392 new webpack.optimize.CommonsChunkPlugin({ name: 'app', async: 'async-vendor', children: true, minChunks: 3 }) ] }
升级到webpack 4后的配置
module.exports = { ... optimization: { splitChunks: { cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, chunks: 'initial', name: 'vendors', }, 'async-vendors': { test: /[\\/]node_modules[\\/]/, minChunks: 2, chunks: 'async', name: 'async-vendors' } } }, runtimeChunk: { name: 'runtime' } }, plugins: [ new webpack.HashedModuleIdsPlugin(), new webpack.NamedChunksPlugin(chunk => chunk.name || 'faceless-chunk'), // a chunk has no name!!! ... ] }