【问题标题】:Cannot use process.env in React component, but can import it in webpack.config.js无法在 React 组件中使用 process.env,但可以在 webpack.config.js 中导入
【发布时间】:2019-02-26 23:44:02
【问题描述】:

我的 React 应用不是使用“create-react-app”构建的。

我能够从 webpack.config.js 控制台记录我使用 dotenv 库从 .env 文件导入和解析的进程环境。

但是,“npm run build”失败。当我用 URL 字符串替换变量时,'npm run build' 通过。

webpack.config.js

const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const dotenv = require('dotenv').config({path: 'config/docker/production/.env'});

// call dotenv and it will return an Object with a parsed key 
const env = dotenv.parsed;

// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});

console.log(process.env.API_URL); -> prints out http://localhost:5000/api/something

const config = {
    entry:  __dirname + '/static/js/index.jsx',
    output: {
        path: __dirname + '/static/dist',
        filename: 'bundle.js',
    },
    resolve: {
        extensions: [".js", ".jsx", ".css"]
    },
    module: {
        rules: [
            {
                test: /\.jsx?/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            path: __dirname + '/static/dist',
            filename: 'styles.css',
        }),
        new webpack.DefinePlugin(envKeys)
    ]
};

module.exports = config;

package.json

  "scripts": {
    "build": "webpack --mode production -p --progress --config webpack.config.js"
  }

config/docker/production/.env

API_URL=http://]ocalhost:5000/api/something

MyComp.jsx

import React,{ Component } from 'react';

class MyComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      races: []};
  }

  componentDidMount(){
    fetch({process.env.API_URL}) -> FAILS
    fetch('http://localhost:5000/api/something') -> PASSES
      .then(results => results.json()) 
      .then(data => this.setState({ races: data.data }));

  }

  render() {
      ...
  }
}

export default MyComp;

【问题讨论】:

    标签: node.js reactjs webpack environment-variables


    【解决方案1】:

    从你的 webpack 配置文件的第 10 行删除“process.env”

    prev[`process.env.${next}`] = JSON.stringify(env[next]);
    

    prev[`${next}`] = JSON.stringify(env[next]);
    

    并直接使用“API_URL”变量而不使用 process.env。

    你可以阅读DefinePluginhere的webpack文档

    另一个问题可能是您如何使用“process.env.API_URL”。 应该是:

    fetch(`${process.env.API_URL}`)
    

    查看勾号和美元符号。

    【讨论】:

      【解决方案2】:

      您应该使用dotenv-webpack webpack 插件将环境变量暴露给您的React 应用程序。

      安装:

      npm i -D dotenv-webpack
      

      用法:

      // webpack.config.js
      
      const Dotenv = require('dotenv-webpack');
      
      module.exports = {
        ...
        plugins: [
          new Dotenv({
            path: 'config/docker/production/.env',
          }),
        ]
        ...
      };
      

      【讨论】:

        猜你喜欢
        • 2019-12-11
        • 2020-11-04
        • 2019-07-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 2017-01-10
        相关资源
        最近更新 更多