webpack_08(区分开发环境)
启动时如何可以区分不同的配置呢?
方案一:编写两个不同的配置文件,开发和生成时,分别加载不同的配置文件即可;
方式二:使用相同的一个入口配置文件,通过设置参数来区分它们;
入口文件解析
我们之前编写入口文件的规则是这样的:./src/index.js,但是如果我们的配置文件所在的位置变成了 config 目录,
我们是否应该变成 ../src/index.js呢?
如果我们这样编写,会发现是报错的,依然要写成 ./src/index.js;
这是因为入口文件其实是和另一个属性时有关的 context;
context的作用是用于解析入口(entry point)和加载器(loader):
官方说法:默认是当前路径(但是经过我测试,默认应该是webpack的启动目录)
区分开发和生成环境配置
创建三个文件:
webpack.comm.conf.js
webpack.dev.conf.js
webpack.prod.conf.js
#webpack.comm.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { DefinePlugin } = require('webpack')
const { VueLoaderPlugin } = require('vue-loader/dist/index')
module.exports = {
target: 'web',
entry: './src/main.js',
output: {
path: path.resolve(__dirname, '../dist'),
filename: 'index.js'
},
resolve: {
extensions: ['.js', '.json', '.mjs', '.vue', '.ts', '.jsx', '.tsx'],
alias: {
'@': path.resolve(__dirname, '../src'),
'js': path.resolve(__dirname, '../src/js')
}
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
},
// },
{
test: /\.(jpe?g|png|gif|svg)$/,
type: 'asset',
generator: {
filename: 'img/[name]_[hash:6][ext]'
},
parser: {
dataUrlCondition: {
maxSize: 20 * 1024
}
}
},
{
test: /\.(eot|ttf|woff2?)$/,
type: 'asset/resource',
generator: {
filename: 'font/[name]_[hash:6][ext]'
}
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
title: 'Webpack'
}),
new DefinePlugin({
BASE_URL: "'./'",
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false
}),
new VueLoaderPlugin()
]
}
#webpack.dev.config.js
const { merge } = require('webpack-merge')
const commonConfig = require('./webpack.comm.config')
module.exports = merge(commonConfig, {
mode: 'development',
devtool: 'source-map',
devServer: {
contentBase: './public',
hot: true,
// host: "0.0.0.0",
port: 7777,
// open: true,
// compress: true,
proxy: {
'/api': {
target: 'http://localhost:8888',
pathRewrite: {
'^/api': ''
},
secure: false,
changeOrigin: true
}
}
}
})
#webpack.prod.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { merge } = require('webpack-merge')
const commonConfig = require('./webpack.comm.config')
module.exports = merge(commonConfig, {
mode: 'production',
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{
from: './public',
globOptions: {
ignore: ['**/index.html']
}
}
]
})
]
})

浙公网安备 33010602011771号