depends on nodejs
Create a demo directory
mkdir webpack-demo && cd webpack-demo npm init -y npm install --save-dev webpack
#Proxy the interface to the local
devServer.proxy
# code splitting
Complete two types of separation work:
1. Separate resources, realize cache resources and load resources in parallel
1) Separating 3rd party libraries as they remain largely unchanged and can be cached on the user's machine for a long time.
How to separate vendor/library code using CommonsChunkPlugin
Using the webpack configuration above, we see that three bundles are generated: vendor
, main
andmanifest
vendor:第三方库
main:应用代码
manifest:webpack runtime 代码,用来帮助 webpack 完成其工作
长效的 bundle 缓存是通过“基于内容的 hash 策略”来实现的(content-based hashing)
需要在
webpack.config.js中修改配置:
var webpack = require('webpack'); var path = require('path'); module.exports = function(env) { return { entry: { main: './index.js', vendor: 'moment' }, output: { filename: '[chunkhash].[name].js', path: path.resolve(__dirname, 'dist') }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'] // Specifies the name of the public bundle. }) ] } };
2) Separate CSS
How to use ExtractTextWebpackPlugin
to separate css
Originally , when webpack packaged CSS, it used css-loader (it outputs CSS as a JS module). The disadvantage of this is that it will not be able to take advantage of the browser's ability to load CSS asynchronously and in parallel, and the web page must wait until your entire JavaScript package is downloaded. Done, then redraw the web page. Then separating the css solves the problem.
Just webpack.config.js
add two steps to the file.
module.exports = { module: { rules: [{ test: /\.css$/, - use: 'css-loader' + use: ExtractTextPlugin.extract({ + use: 'css-loader' + }) }] }, + plugins: [ + new ExtractTextPlugin('styles.css'), + ] }
3) Separation on demand (dynamic separation, the first two are pre-specified separation modules in the configuration)
How to use require.ensure()
to separate code
require.ensure(dependencies: String[], callback: function(require), chunkName: String)