我一直在尝试在React中加载环境变量,但似乎无法弄清楚。我尝试了多种方法:
使用dotenv-webpack
包加载它们
webpack.config.dev.js
const merge = require('webpack-merge'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const template = require('html-webpack-template'); const Dotenv = require('dotenv-webpack'); const baseCOnfig= require('./webpack.config.base'); module.exports = merge(baseConfig, { mode: 'production', plugins: [ new HtmlWebpackPlugin({ template, inject: false, appMountId: 'app', mobile: true, lang: 'es-ES', title: 'My App', meta: [ { name: 'description', content: 'My App', }, ], }), new Dotenv(), ], });
.env
API_HOST=http://localhost:8000 REACT_APP_API_HOST=http://localhost:8000
将其直接传递给package.json
脚本:
"start": "webpack-dev-server --config ./webpack.config.dev.js"
在webpack命令上使用.env
webpack --env.API_HOST=http://localhost:8000
使用 webpack.environmentPlugin
const webpack = require('webpack'); const merge = require('webpack-merge'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const template = require('html-webpack-template'); const baseCOnfig= require('./webpack.config.base'); module.exports = merge(baseConfig, { mode: 'development', devtool: 'cheap-module-source-map', devServer: { publicPath: '/', contentBase: './dist', compress: true, stats: 'minimal', overlay: true, historyApiFallback: true, port: 8081, hot: true, }, plugins: [ new HtmlWebpackPlugin({ template, devServer: 'http://localhost:8081', inject: false, appMountId: 'app', mobile: true, lang: 'es-ES', title: 'My App', meta: [ { name: 'description', content: 'React template.', }, ], }), new webpack.EnvironmentPlugin({ API_HOST: 'http://localhost:8000', }), ], });
这些方法都不起作用,当我尝试process.env
在React代码中访问变量时,我得到undefined
关于可能做错什么的任何想法?