简体   繁体   English

使用 webpack 构建应用程序时如何更改 NODE_ENV?

[英]How to change NODE_ENV when building app with webpack?

I have a .env file that contains the NODE_ENV variable.我有一个包含NODE_ENV变量的.env文件。 Per default, it is set to development .默认情况下,它设置为development When building the React app with webpack, I launch the command yarn build :使用 webpack 构建 React 应用程序时,我启动命令yarn build

 "scripts": { "start": "NODE_ENV=development webpack serve --open --hot", "build": "NODE_ENV=production && webpack", }

The .env file is: .env文件是:

 NODE_ENV = "development"

But when logging the NODE_ENV value in my webpack configuration file, I can see it is still in development .但是在我的 webpack 配置文件中记录NODE_ENV值时,我可以看到它仍在development中。 The build is not minified either.构建也没有缩小。 But when I write production in my .env file, everything works fine.但是当我在.env文件中编写production时,一切正常。

The webpack configuration is: 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", }, }, }; };

The question is thus: how to make sure I can change my NODE_ENV when launching the build?因此问题是:如何确保在启动构建时可以更改我的NODE_ENV

Also, what is the command I should write in my package.json to launch the build once the dist folder is uploaded to Netlify or similar hosting platform?另外,一旦将 dist 文件夹上传到 Netlify 或类似的托管平台,我应该在 package.json 中编写什么命令来启动构建?

Thanks!谢谢!

Try checking for process.env.NODE_ENV instead of env.parsed.NODE_ENV if you want to take environment variables passed on the command line into account.如果您想考虑命令行上传递的环境变量,请尝试检查process.env.NODE_ENV而不是env.parsed.NODE_ENV These will be exposed as properties on process.env - and will take precedence over variables loaded from the.env file there - but not on the parsed property of the object returned by require("dotenv").config() .这些将作为process.env上的属性公开 - 并将优先于从那里的 .env 文件加载的变量 - 但不会在require("dotenv").config()返回的 object 的parsed属性上。 These two objects actually are not kept in sync.这两个对象实际上并没有保持同步。

You can try this simple node program:你可以试试这个简单的节点程序:

process.env.NODE_ENV = "production"   // simulate command line environment variable
var env = require("dotenv").config()

console.log(process.env.NODE_ENV)     // output: "production"
console.log(env.parsed.NODE_ENV)      // output: "development"

// .env
NODE_ENV=development

Edit: just for completion, just make sure you use the syntax that is right for your OS to set up environment variables on the command line, or use the OS-agnostic cross-env package for this purpose.编辑:只是为了完成,只需确保您使用适合您的操作系统的语法在命令行上设置环境变量,或为此目的使用与操作系统无关cross-env环境 package。

// package.json
"scripts": {
  "build:dev": "webpack",
  "build:prod": "cross-env NODE_ENV=production webpack"
},

// .env
NODE_ENV=development

// webpack.config.js
const dotenv = require("dotenv")

dotenv.config()
console.log(process.env.NODE_ENV)

process.exit(0)

// console output
npm run build:dev      // "development"
npm run build:prod     // "production"

Else, as I pointed out in the comment below, you can use the --node-env flag to set the NODE_ENV environment variable with the webpack CLI.否则,正如我在下面的评论中指出的那样,您可以使用--node-env标志通过 webpack CLI 设置NODE_ENV环境变量。

"build:prod": "webpack --node-env=production"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM