简体   繁体   中英

How to change NODE_ENV when building app with webpack?

I have a .env file that contains the NODE_ENV variable. Per default, it is set to development . When building the React app with webpack, I launch the command yarn build :

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

The .env file is:

 NODE_ENV = "development"

But when logging the NODE_ENV value in my webpack configuration file, I can see it is still in development . The build is not minified either. But when I write production in my .env file, everything works fine.

The webpack configuration is:

 /* 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?

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?

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. 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() . 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.

// 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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