[英]env-vars in React using Dotenv and Webpack
我想訪問前端(反應)中定義的一些環境變量。
我有以下設置:
create-react-app
) 我嘗試遵循https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5#0618,但是它不起作用,或者拋出任何錯誤。
webpack.config.js
const dotenv = require("dotenv");
module.exports = () => {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
console.log(prev)
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
...,
plugins: [
new webpack.DefinePlugin(envKeys)
],
...
}
通過上面的WebPack的配置,我想我應該能夠做到<h4>My var: {process.env.REACT_APP_MY_VAR}</h4>
在file.js
,當然我已經定義REACT_APP_MY_VAR
我.env
位於項目-file根。
通過上面我希望file.js
呈現的價值REACT_APP_MY_VAR
,但我確實沒有渲染,無論是價值還是錯誤。
我建議您使用dotenv-webpack
而不是dotenv
軟件包,以方便配置。
4個簡單步驟:
1)使用安裝dotenv-wepack
npm install dotenv-webpack --save
2)在應用程序的根目錄下創建.env
文件
API_URL=http://localhost:8000
3)將此添加到您的webpack配置文件。
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
4)在應用程序內的任何地方使用env變量。
import React from 'react';
const App = () => {
return (
<h1>{process.env.API_URL}</h1>
);
}
export default App;
希望有幫助!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.