我想在开发和生产中使用另一个.env文件。
对于生产构建,我使用npm run build:production,对于开发,我使用npm run start。
但我没有使用环境变量。
在我的项目中,现在不使用env文件。所以当我构建项目时,我应该修改一些代码。
我想使用env文件。
例:
开发:.env.dev
BASE_URL=http://localhost:3000生产:.dnv.prod
BASE_URL=https://aaa.compackage.json
"scripts": {
"start": "webpack-dev-server",
"build": "webpack --progress --config webpack.config.ts",
"build:production": "webpack -p --progress --config webpack.config.ts",
"test": "echo \"Error: no test specified\" && exit 1"
}webpack.config.ts
const config = {
entry: [
'react-hot-loader/patch',
'./src/index.tsx',
'./assets/styles/main.scss'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
devtool: 'source-map',
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.css', '.scss', '.json']
},
plugins: [
new Dotenv(),
new HtmlWebpackPlugin({
title: 'Hubbers v2',
chunksSortMode: 'dependency',
template: path.resolve(__dirname, './src/index.html')
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExtractTextWebpackPlugin('main.css'),
new CopyWebpackPlugin([
{from: 'assets/images', to: 'images'},
{from: 'assets/icons', to: 'icons'},
{from: 'src/_redirects', to: ''}
]),
new webpack.ContextReplacementPlugin(
/moment[/\\]locale$/,
/eu|cn/
)
],
module: {
loaders: [
{
test: /\.(png|jp(e*)g|webp|gif)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.woff(2)?(\?[a-z0-9]+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
},
{
test: /\.(ttf|eot|otf|svg)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
},
{
test: /\.(css|scss)/,
use: ['css-hot-loader', ...ExtractTextWebpackPlugin.extract({
use: [
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
options: {
includePaths: [...require('bourbon').includePaths, ...require('bourbon-neat').includePaths]
}
}
]
})]
},
{
test: /\.json$/, loader: 'json-loader'
},
{
test: /\.tsx?$/,
loaders: [
'react-hot-loader/webpack',
'awesome-typescript-loader'
],
exclude: path.resolve(__dirname, 'node_modules'),
include: path.resolve(__dirname, 'src')
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader'
}
]
},
devServer: {
hot: true,
inline: true,
historyApiFallback: true
}
}
export default config发布于 2020-12-02 21:24:16
我看到你使用多滕诺夫-webpack。它支持指定路径参数。您可以通过env变量设置路径参数(听起来很讽刺-为了加载ENV变量,您需要一个ENV变量.)。
因此,您需要将path参数添加到Dotenv构造函数中,并根据process.env.NODE_ENV变量设置文件:
{
plugins: [
new new Dotenv({
path: process.env.NODE_ENV === 'production' ? '.dnv.prod' : '.env.dev'
})
]
}然后,您需要更新脚本以将NODE_ENV变量添加到webpack (文档):
{
"scripts": {
"build": "webpack --env NODE_ENV=development --progress --config webpack.config.ts",
"build:production": "webpack --env NODE_ENV=production -p --progress --config webpack.config.ts",
}
}https://stackoverflow.com/questions/65116173
复制相似问题