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

时间:2018-09-23 03:46:38

标签: node.js reactjs webpack environment-variables

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

我能够从webpack.config.js进行console.log,该过程环境是我使用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;

2 个答案:

答案 0 :(得分:1)

您应该使用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',
    }),
  ]
  ...
};

答案 1 :(得分:0)

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

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

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

,并直接使用“ API_URL”变量,而无需process.env。

您可以阅读DefinePlugin here的Webpack文档

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

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

请参阅刻度线和美元符号。