我有一个包含NODE_ENV
变量的.env
文件,默认情况下,它被设置为development
。在使用webpack构建React应用程序时,我启动命令yarn build
:
"scripts": {
"start": "NODE_ENV=development webpack serve --open --hot",
"build": "NODE_ENV=production && webpack",
}
.env
文件为:
NODE_ENV = "development"
但是当我在webpack配置文件中记录NODE_ENV
值时,我可以看到它仍然在development
中,构建也没有缩小,但是当我在.env
文件中写入production
时,一切都正常。
Webpack配置为:
/* eslint-env node */
const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const Dotenv = require("dotenv-webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const isProductionMode = (mode) => mode === "production";
module.exports = () => {
const env = require("dotenv").config({ path: __dirname + "/.env" });
const nodeEnv = env.parsed.NODE_ENV;
console.log("🛎🛎🛎 isProduction", isProductionMode(nodeEnv)) // output: false
return {
mode: nodeEnv,
entry: "./src/index.tsx",
output: {
path: path.join(__dirname, "./dist"),
filename: "[name].[contenthash].bundle.js",
publicPath: "/",
clean: true,
},
resolve: {
extensions: [".ts", ".tsx", ".js", "jsx", ".json"],
alias: {
api: path.resolve(__dirname, "src/api/"),
assets: path.resolve(__dirname, "src/assets/"),
components: path.resolve(__dirname, "src/components/"),
containers: path.resolve(__dirname, "src/containers/"),
data: path.resolve(__dirname, "src/data/"),
i18n: path.resolve(__dirname, "src/i18n/"),
models: path.resolve(__dirname, "src/models/"),
pages: path.resolve(__dirname, "src/pages/"),
routes: path.resolve(__dirname, "src/routes/"),
src: path.resolve(__dirname, "src/"),
stores: path.resolve(__dirname, "src/stores/"),
utils: path.resolve(__dirname, "src/utils/"),
},
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: { loader: "babel-loader" },
},
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.(png|jpg|jpeg|woff2)$/, use: ["file-loader"] },
{
test: /\.svg$/,
use: [
{ loader: "babel-loader" },
{
loader: "react-svg-loader",
options: {
jsx: true,
},
},
],
},
],
},
devServer: {
historyApiFallback: true,
port: 3000,
inline: true,
hot: true,
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
favicon: "./src/assets/images/favicon.png",
}),
new Dotenv(),
],
optimization: {
minimize: isProductionMode(nodeEnv),
minimizer: isProductionMode(nodeEnv)
? [new TerserPlugin(), new CssMinimizerPlugin()]
: [],
splitChunks: {
chunks: "all",
},
},
};
};
因此,问题是:如何确保我可以在启动构建时更改我的NODE_ENV
?
另外,当dist文件夹上传到Netlify或类似的托管平台时,我应该在package.json
中编写什么命令来启动构建?
1条答案
按热度按时间rdlzhqv91#
如果你想考虑命令行传递的环境变量,尝试检查
process.env.NODE_ENV
而不是env.parsed.NODE_ENV
。这些将作为process.env
的属性公开-并且将优先于从那里的.env文件加载的变量-但是不在require("dotenv").config()
返回的对象的parsed
属性上。这两个对象实际上并不保持同步。你可以试试这个简单的节点程序:
编辑:为了完成,请确保使用适合您的操作系统的语法在命令行上设置环境变量,或者使用与操作系统无关的
cross-env
包来实现此目的。另外,正如我在下面的评论中指出的,您可以使用
--node-env
标志通过webpack CLI设置NODE_ENV
环境变量。