Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 无法在React组件中使用process.env,但可以在webpack.config.js中导入它_Node.js_Reactjs_Webpack_Environment Variables - Fatal编程技术网

Node.js 无法在React组件中使用process.env,但可以在webpack.config.js中导入它

Node.js 无法在React组件中使用process.env,但可以在webpack.config.js中导入它,node.js,reactjs,webpack,environment-variables,Node.js,Reactjs,Webpack,Environment Variables,我的React应用程序不是使用“创建React应用程序”生成的 我能够从webpack.config.js中console.log使用dotenv库从.env文件导入和解析的流程环境 但是,“npm运行生成”失败。当我用URL字符串替换变量时,“npm run build”传递 webpack.config.js const webpack = require('webpack'); const MiniCssExtractPlugin = require("mini-css-extract-p

我的React应用程序不是使用“创建React应用程序”生成的

我能够从webpack.config.js中console.log使用dotenv库从.env文件导入和解析的流程环境

但是,“npm运行生成”失败。当我用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;
您应该使用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',
    }),
  ]
  ...
};
用法:

npm i -D dotenv-webpack
// webpack.config.js

const Dotenv = require('dotenv-webpack');

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: 'config/docker/production/.env',
    }),
  ]
  ...
};

从网页包配置文件的第10行删除“process.env”

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

并直接使用'API_URL'变量,而不使用process.env

您可以阅读DefinePlugin的网页文档

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

fetch(`${process.env.API_URL}`)
请看勾号和美元符号