入口起点分离: 使用 entry 手动的分离代码。(配置多,并且有一些隐患,不建议使用)
project
webpack-demo |- package.json |- webpack.common.js
|- webpack.prod.js
|- webpack.dev.js |- /dist |- /src |- index.js |- another-module.js |- /node_modules
another-module.js
import _ from 'lodash' console.log( _.join(['Another', 'module', 'loaded!'], ' ') )
index.js
import _ from 'lodash' function component () { const element = document.createElement('div') element.innerHTML = _.join(['Hello', 'webpack'], ' ') return element } document.body.appendChild(component())
webpack.common.js
使用 optimization.splitChunks 防止重复模块
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const { CleanWebpackPlugin } = require('clean-webpack-plugin') // 从 webpack v4 开始,移除了 CommonsChunkPlugin,取而代之的是 optimization.splitChunks module.exports = { entry: { index: './src/index.js', another: './src/another-module.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, plugins: [ new HtmlWebpackPlugin(), new CleanWebpackPlugin() ], optimization: { splitChunks: { /** * 1. async,默认值,表示异步引入的模块 * 2. initial,同步引入的模块 * 3. all,两者皆可 */ chunks: 'all' } } }
webpack.dev.js
const {merge} = require('webpack-merge') const common = require('./webpack.common') module.exports = merge(common, { mode: 'development', devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 3000, open: true } })
webpack.prod.js
const {merge} = require('webpack-merge') const common = require('./webpack.common') module.exports = merge(common, { mode: 'development', devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 3000, open: true } })