webpack的基本配置
2021-12-25 本文已影响0人
时间的溺水者
package.json中配置对应关系
image.png image.png
1、拆分和合并配置
可以将不同配置环境的配置拆分至不同的文件夹中,相同的配置抽离成一个公共配置文件中,比如下图
image.png
其中webpack.common.js则为公共组件、webpack.dev.js为开发环境配置、webpack.prod.js为正式环境配置
webpack.common.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { srcPath, distPath } = require('./paths')
module.exports = {
entry: path.join(srcPath, 'index'),
plugins: [
new HtmlWebpackPlugin({
template: path.join(srcPath, 'index.html'),
filename: 'index.html'
})
],
}
webpack.dev.js
const path = require('path')
const webpack = require('webpack')
const webpackCommonConf = require('./webpack.common.js')
const { merge } = require('webpack-merge')
const { srcPath, distPath } = require('./paths')
module.exports = merge(webpackCommonConf, {
mode: 'development',
devServer: {
historyApiFallback: true,
contentBase: distPath,
open: true,
compress: true,
hot: true,
port: 8080,
// 设置代理 —— 如果有需要的话!
proxy: {
// 将本地 /api/xxx 代理到 localhost:3000/api/xxx
'/api': 'http://localhost:3000',
// 将本地 /api2/xxx 代理到 localhost:3000/xxx
'/api2': {
target: 'http://localhost:3000',
pathRewrite: {
'/api2': ''
}
}
}
},
plugins: [
new webpack.DefinePlugin({
// window.ENV = 'production'
ENV: JSON.stringify('development')
})
]
})
webpack.prod.js
const path = require('path')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpackCommonConf = require('./webpack.common.js')
const { merge } = require('webpack-merge')
const { srcPath, distPath } = require('./paths')
module.exports = merge(webpackCommonConf, {
mode: 'production',
output: {
filename: 'bundle.[contenthash:8].js', // 打包代码时,加上 hash 戳
path: distPath,
// publicPath: 'http://cdn.abc.com' // 修改所有静态文件 url 的前缀(如 cdn 域名),这里暂时用不到
},
plugins: [
new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
new webpack.DefinePlugin({
// window.ENV = 'production'
ENV: JSON.stringify('production')
})
]
})
在webpack.dev.js和webpack.prod.js文件中通过
const webpackCommonConf = require('./webpack.common.js')引入各自文件中
在通过引用webpack-merge中的merge 合并至各自的环境配置中
image.png在webpack4版本中使用smart进行合并
image.png