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

gmol1639  于 2023-03-12  发布在  Node.js
关注(0)|答案(1)|浏览(248)

我有一个包含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中编写什么命令来启动构建?

rdlzhqv9

rdlzhqv91#

如果你想考虑命令行传递的环境变量,尝试检查process.env.NODE_ENV而不是env.parsed.NODE_ENV。这些将作为process.env的属性公开-并且将优先于从那里的.env文件加载的变量-但是不在require("dotenv").config()返回的对象的parsed属性上。这两个对象实际上并不保持同步。
你可以试试这个简单的节点程序:

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

编辑:为了完成,请确保使用适合您的操作系统的语法在命令行上设置环境变量,或者使用与操作系统无关的cross-env包来实现此目的。

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

另外,正如我在下面的评论中指出的,您可以使用--node-env标志通过webpack CLI设置NODE_ENV环境变量。

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

相关问题