webpack配置篇
开发环境(development)和生产环境(production)的构建目标差异很大。在开发环境中,我们需要具有强大的、具有实时重新加载(live reloading)或热模块替换(hot module replacement)能力的 source map 和 localhost server。而在生产环境中,我们的目标则转向于关注更小的 bundle,更轻量的 source map,以及更优化的资源,以改善加载时间。
遵循逻辑分离,我们通常建议为每个环境编写彼此独立的 webpack 配置。为了减少重复的代码,将配置中可复用的部分抽离出来。
1.安装 webpack-merge
npm install --save-dev webpack-merge
2.更改目录结构
webpack.common.js
const path = require('path'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './src/index.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, module:{ rules:[ { test:/\.css/, use:[ 'style-loader', 'css-loader' ] } ] }, plugins:[ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: 'output management' }) ] }
webpack.dev.js
const merge = require('webpack-merge'); const common = require('./webpack.common'); const webpack = require('webpack'); module.exports = merge(common, { mode: 'development', devtool: "inline-source-map", devServer: { contentBase: './dist', hot: true, }, plugins: [ new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin(), ] })
webpack.prod.js
const merge = require('webpack-merge'); const common = require('./webpack.common'); module.exports = merge(common,{ mode: 'production' })
对于开发环境的压缩,在控制台使用
--optimize-minimize
标记将在后台引用UglifyJSPlugin
。--define process.env.NODE_ENV="'production'"
将在后台调用与DefinePlugin
实例。webpack -p
将自动地调用所需要引入的插件。