企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 配置 *开发环境(development)* 和 *生产环境(production)* 的构建目标差异很大。在*开发环境*中,我们需要具有强大的、具有实时重新加载(live reloading)或热模块替换(hot module replacement)能力的 source map 和 localhost server。而在*生产环境*中,我们的目标则转向于关注更小的 bundle,更轻量的 source map,以及更优化的资源,以改善加载时间。由于要遵循逻辑分离,我们通常建议为每个环境编写**彼此独立的 webpack 配置**。 虽然,以上我们将*生产环境*和*开发环境*做了略微区分,但是,请注意,我们还是会遵循不重复原则(Don't repeat yourself - DRY),保留一个“通用”配置。为了将这些配置合并在一起,我们将使用一个名为 [`webpack-merge`](https://github.com/survivejs/webpack-merge) 的工具。通过“通用”配置,我们不必在环境特定(environment-specific)的配置中重复代码。 我们先从安装 `webpack-merge` 开始,并将之前指南中已经成型的那些代码再次进行分离: ``` yarn add webpack-merge -D ``` 新建 `conf/webpack.prod.js` ```js const merge = require('webpack-merge'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const webpackBaseConf = require('./webpack.base.js'); module.exports = merge(webpackBaseConf, { plugins: [ new UglifyJSPlugin({ sourceMap: true }) ] }); ``` 新建 `conf/webpack.dev.js` ```js const path = require('path'); const merge = require('webpack-merge'); const webpackBaseConf = require('./webpack.base.js'); module.exports = merge(webpackBaseConf, { devtool: 'inline-source-map', devServer: { contentBase: path.join(__dirname, "..", "dist"), // 服务器根目录 compress: true, // 压缩 port: 9000, // 监听端口 open: true, // 直接使用浏览器打开 hot: true } }); ``` 修改 `conf/webpack.base.js` ```js const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const config = { entry: { main: './src/main.js', vendor: [ 'lodash' ] }, output: { path: path.resolve(__dirname, '..', 'dist'), filename: '[name].[hash].js', publicPath: '/' }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'url-loader' ] } ] }, plugins: [ new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin(), new CleanWebpackPlugin(['dist'], { root: path.resolve(__dirname, '..'), exclude: ['manifest.json'], verbose: true, dry: false }), new HtmlWebpackPlugin({ title: 'Output Management', filename: 'index.html', template: 'index.html' }), new HtmlWebpackPlugin({ // Also generate a test.html filename: 'static/test.html', // template: 'src/static/test.html' }), new webpack.HashedModuleIdsPlugin(), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor' }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' }), new ManifestPlugin() ] }; module.exports = config; ``` 修改 `package.json` ```json "scripts": { "start": "webpack-dev-server --config conf/webpack.dev.js", "build": "webpack --config conf/webpack.prod.js", "watch": "webpack --watch --config conf/webpack.dev.js", "server": "node conf/server.js", "push": "npm run build && git add * && git commit -am 0 && git push origin master" } ```