【发布时间】:2021-03-14 21:21:30
【问题描述】:
我想在开发和生产中使用另一个 .env 文件。
对于生产构建,我使用npm run build:production,对于开发,我使用npm run start。
但我没有使用环境变量。
在我的项目中,现在不使用 env 文件。所以当我构建项目时,我应该更改一些代码。
我想使用 env 文件。
例如:
-
开发环境
npm 运行开发
-
生产环境
npm 运行产品
发展: .env.dev
BASE_URL=http://localhost:3000
生产: .dnv.prod
BASE_URL=https://aaa.com
package.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
【问题讨论】:
-
看看 dotenv 和他们的path option
标签: reactjs typescript webpack environment-variables