简体   繁体   English

同构JS应用程序中的环境变量:Webpack查找和替换?

[英]Environment Variables in an isomorphic JS app: Webpack find & replace?

I'm using webpack to bundle an isomorphic JS app ( based on this example ) so that the browser runs the same code as the server. 我正在使用webpack捆绑一个同构的JS应用程序( 基于此示例 ),以便浏览器运行与服务器相同的代码。 Everything is running smoothly except I have a config.js with some settings which are pulled in from environment variables on the server: 一切都运行顺利,除了我有一个config.js ,其中有一些设置是从服务器上的环境变量中提取的:

module.exports = {
  servers:
    auth: process.env.AUTH_SERVER_URL,
    content: process.env.CONTENT_SERVER_URL
  }
}

On the server this is grand, but when webpack renders this for the client process is empty and this doesn't work. 在服务器上这是盛大的,但是当webpack为客户端process呈现这个时,它是空的,这不起作用。

I'm hoping there's a kind of 'find and replace' webpack plugin that will replace them with their content in that file alone? 我希望有一种'查找和替换'webpack插件,它将仅用该文件中的内容替换它们?

"…config.js content…".replace(/process\.env\.([a-z0-9_]+)/, function(match, varName) {
  return process.env[varName];
})

Note that using the DefinePlugin as suggested in the accepted answer is potentially a dangerous action as it completely exposes process.env . 请注意,在接受的答案中建议使用DefinePlugin可能是一个危险的操作,因为它完全暴露了process.env As Tobias commented above there's actually a plugin EnvironmentPlugin that does exactly this with an added whitelisting ability, using DefinePlugin internally. 正如Tobias在上面评论的那样,实际上有一个插件EnvironmentPlugin可以在内部使用DefinePlugin增加白名单功能。

In your webpack.config.js : 在你的webpack.config.js

{
  plugins: [
    new webpack.EnvironmentPlugin([
      'NODE_ENV',
      'WHITELISTED_ENVIRONMENT_VARIABLE'
    ])
  ]
}

In your webpack.config.js , use the following preLoaders (or postLoaders ), 在您的webpack.config.js ,使用以下preLoaders (或postLoaders ),

  module: {
    preLoaders: [
      { test: /\.js$/, loader: "transform?envify" },
    ]
  }

Another way using the webpack.DefinePlugin : 使用webpack.DefinePlugin另一种方法:

plugins: [
    new DefinePlugin({
      'process.env': Object.keys(process.env).reduce(function(o, k) {
        o[k] = JSON.stringify(process.env[k]);
        return o;
      }, {})
    })
]

NOTE : The old method using envify-loader was deprecated: 注意 :不推荐使用envify-loader的旧方法:

DEPRECATED : use transform-loader + envify instead. DEPRECATED :改为使用transform-loader + envify

Yeah; 是啊; looks like envify-loader was the easy solution. 看起来像envify-loader是一个简单的解决方案。

I just added the following to my webpack loaders: 我刚刚将以下内容添加到我的webpack加载器中:

{
  test: /config\.js$/, loader: "envify-loader"
}

And the config.js (and only that file) is modified to include any referenced environment variables statically :) 并修改config.js (并且只有该文件)以静态包含任何引用的环境变量:)

I needed a way to use the env variables set on the machine that is running the code, no the env variables of the machine building the app. 我需要一种方法来使用运行代码的机器上设置的env变量,而不是构建应用程序的机器的env变量。

I do not see a solution for this yet. 我还没有看到解决方案。 This is what I did. 这就是我做的。

In publicEnv.js : publicEnv.js

// List of the env variables you want to use on the client. Careful on what you put here!
const publicEnv = [
  'API_URL',
  'FACEBOOK_APP_ID',
  'GA_ID'
];

const isBrowser = typeof window !== 'undefined';
const base = (isBrowser ? window.__ENV__ : process.env) || {};

const env = {};
for (const v of publicEnv) {
  env[v] = base[v];
}
export default env;

In the HTML template file of the page I have: 在我的页面的HTML模板文件中:

import publicEnv from 'publicEnv.js';

...

<script>
  window.__ENV__ = ${stringify(publicEnv)};

  // Other things you need here...
  window.__INITIAL_STATE__ = ${stringify(initialState)};
</script>

So now I can get the value of the env variable on both frontend and backend with: 所以现在我可以在前端和后端获得env变量的值:

import publicEnv from 'publicEnv.js';

...

console.log("Google Analytic code is", publicEnv.GA_ID);

I hope it can help. 我希望它可以提供帮助。

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

相关问题 带有 Webpack 的 Typescript 中的环境变量 - Environment variables in Typescript with Webpack 修复同构JS应用中的把手编译问题 - Fixing Handlebars compile issue in isomorphic JS app moment.js-通用(同构)js应用程序中的fromNow()方法 - momentjs - fromNow() method in universal (isomorphic) js app Webpack的同构渲染 - Isomorphic Rendering with Webpack Isomorphic React app - 当JS关闭时如何处理表单提交 - Isomorphic React app - how to handle form submission when JS is off 错误:无法解析JS isomorphic app中的&#39;fs&#39; - Error: Can't resolve 'fs' in JS isomorphic app 如何访问 React JS Web 应用程序中的环境变量? - How to access environment variables inside React JS web app? 在 Node Express App 的不同 js 文件中使用环境变量 - Use Environment Variables in different js File in Node Express App 如何在docker文件中获取对我可用的docker环境变量? (使用React / JS / webpack) - How do I get the docker environment variables available to me in the docker file? (using React/JS/webpack) Dotenv Webpack - 当我在运行时更改系统环境变量时,更改不会影响应用程序 - Dotenv Webpack - When I change the system environment variables on runtime, the changes is not affected on the app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM