简体   繁体   English

process.env.NODE_ENV 在 webpack 4 中返回 undefined,服务器端

[英]process.env.NODE_ENV returns undefined in webpack 4, server-side

in server code I have this:在服务器代码中,我有这个:

import express from "express";
const server = express();
import path from "path";
// const expressStaticGzip = require("express-static-gzip");
import expressStaticGzip from "express-static-gzip";
import webpack from "webpack";
import webpackHotServerMiddleware from "webpack-hot-server-middleware";

import configDevClient from "../../config/webpack.dev-client";
import configDevServer from "../../config/webpack.dev-server.js";
import configProdClient from "../../config/webpack.prod-client.js";
import configProdServer from "../../config/webpack.prod-server.js";

const isProd = process.env.NODE_ENV === "production";
const isDev = !isProd;
const PORT = process.env.PORT || 8000;
let isBuilt = false;

const done = () => {
  !isBuilt &&
    server.listen(PORT, () => {
      isBuilt = true;
      console.log(
        `Server listening on http://localhost:${PORT} in ${process.env.NODE_ENV}`
      );
    });
};

if (isDev) {
  const compiler = webpack([configDevClient, configDevServer]);

  const clientCompiler = compiler.compilers[0];
  const serverCompiler = compiler.compilers[1];

  const webpackDevMiddleware = require("webpack-dev-middleware")(
    compiler,

    configDevClient.devServer
  );

  const webpackHotMiddlware = require("webpack-hot-middleware")(
    clientCompiler,
    configDevClient.devServer
  );

  server.use(webpackDevMiddleware);
  server.use(webpackHotMiddlware);
  console.log("process.env.NODE_ENV",process.env.NODE_ENV);//RETURNS UNDEFINED
  server.use(webpackHotServerMiddleware(compiler));
  console.log("Middleware enabled");
  done();
} else {
  webpack([configProdClient, configProdServer]).run((err, stats) => {
    const clientStats = stats.toJson().children[0];
    const render = require("../../build/prod-server-bundle.js").default;
    server.use(
      expressStaticGzip("dist", {
        enableBrotli: true
      })
    );
    server.use(render({ clientStats }));
    done();
  });
}

I client and server config files I have this plugin enabled:我启用了此插件的客户端和服务器配置文件:

new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("development"),
        WEBPACK: true
      }

but this is the output但这是输出

process.env.NODE_ENV undefined
Server listening on http://localhost:8000 in undefined

in client side it is working BUT express side process.env.NODE_ENV returns undefined在客户端它正在工作,但表达端 process.env.NODE_ENV 返回未定义

Assuming you using Webpack-Dev-Server, you can use this call syntax witch is proper :假设你使用 Webpack-Dev-Server,你可以使用这个调用语法是正确的:

const dev = Boolean( process.env.WEBPACK_DEV_SERVER )

You will no longer need to pass environment type parameters, because I think you pass parameters in your script run in packages.json您将不再需要传递环境类型参数,因为我认为您在 package.json 中运行的脚本中传递参数

I'm writing my experience to help anyone out there with this problem, though I did not actually solve it.我正在写我的经验来帮助任何人解决这个问题,尽管我并没有真正解决它。 I had the same problem with setting the environment variables in my server-side project.我在服务器端项目中设置环境变量时遇到了同样的问题。

apparently, after you set the environment variables they are completely accessible in the building process, which is in the build tools like webpack config or even .babelrc.js .显然,在您设置环境变量后,它们在构建过程中是完全可以访问的,这在构建工具中,如webpack config甚至.babelrc.js

but after the build process, the environment variables get overwritten AND there is a time gap between build process and overwriting environment variables .但是在构建过程之后,环境变量被覆盖,并且构建过程和覆盖环境变量之间存在时间间隔

I used many webpack or babel plugins but neither of them could hold on to environment variables after the build process ON the server-side but they were immediately defined on the client-side.我使用了许多webpack or babel plugins但在服务器端的构建过程之后,它们都无法保留环境变量,但它们立即在客户端定义。 since I'm using ReactJs , I tried adding REACT_APP_ to the beginning of variables, but still no luck.由于我使用的是ReactJs ,我尝试将REACT_APP_添加到变量的开头,但仍然没有运气。

some other plugins I used: webpack dotenv , webpack.DefinePlugin , webpack.EnvironmentPlugin , babel-plugin-transform-define , babel-plugin-transform-inline-environment-variables我使用的其他一些插件: webpack dotenvwebpack.DefinePluginwebpack.EnvironmentPluginbabel-plugin-transform-definebabel-plugin-transform-inline-environment-variables

so it made me use the good old-fashion way of setting environment.js on DEPLOY but not on the BUILD process.所以它让我使用了在 DEPLOY 上而不是在 BUILD 过程中设置environment.js旧时尚方式。

in case someone is not familiar: you have one main environment.js and (in my case) 2 other files, one for staging environment.staging.js and one for production environment.prod.js .以防有人不熟悉:您有一个主要environment.js和(在我的情况下)2 个其他文件,一个用于staging environment.staging.js ,另一个用于production environment.prod.js On each deploy, you copy the related js to environment.js , the main environment file, and in your code, you always read global CONSTs , baseUrl for APIs and ... from environment.js .在每次部署时,您将相关的js复制到environment.js (主环境文件),并且在您的代码中,您始终读取global CONSTsbaseUrl for APIs global CONSTs和 ...来自environment.js

hope it helps someone out there.希望它可以帮助那里的人。

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

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