在 Strapi 插件中检索环境变量
Retrieve env variables in Strapi plugin
我开发了一个 Strapi local plugin 但我无法在我的项目的根目录中检索我的 .env 文件中定义的变量。我尝试在我的 React 组件中加载这个值 (plugins/myPluginName/admin/src/containers/HomePage/index.js
)。
我尝试使用这样的全局进程模块:
process.env.my_variable
但是returnsundefined
有什么想法吗?
感谢@sunnyson strapi forum I found a solution. By default .env variables are not passed to the client-side. You need to customize webpack config。
这样做:
- 在项目的根目录下创建文件夹
/admin
,然后创建 admin.config.js
.
module.exports = {
webpack: (config, webpack) => {
// Add your variable using the DefinePlugin function
config.plugins.push(
new webpack.DefinePlugin({
// ENVS that you want to use in frontend
CUSTOM_VARIABLES: {
variable1: JSON.stringify(process.env.variable1),
},
})
);
// Return the modified config
return config;
},
};
- 在你的反应组件中,你可以像这样使用你的环境变量:
class HomePage extends React.Component {
constructor(props) {
this.state = {
env: { CUSTOM_VARIABLES }
}
logEnv() {
console.log(this.state.env.variable1)
}
}
显然,管理面板现在支持 dotenv 变量。
只需在您的 .env 变量前加上 STRAPI_ADMIN_ 前缀即可使用 process.env.
例如,.env 中的 STRAPI_ADMIN_KEY
可用作 process.env.STRAPI_ADMIN_KEY
我开发了一个 Strapi local plugin 但我无法在我的项目的根目录中检索我的 .env 文件中定义的变量。我尝试在我的 React 组件中加载这个值 (plugins/myPluginName/admin/src/containers/HomePage/index.js
)。
我尝试使用这样的全局进程模块:
process.env.my_variable
但是returnsundefined
有什么想法吗?
感谢@sunnyson strapi forum I found a solution. By default .env variables are not passed to the client-side. You need to customize webpack config。
这样做:
- 在项目的根目录下创建文件夹
/admin
,然后创建admin.config.js
.
module.exports = {
webpack: (config, webpack) => {
// Add your variable using the DefinePlugin function
config.plugins.push(
new webpack.DefinePlugin({
// ENVS that you want to use in frontend
CUSTOM_VARIABLES: {
variable1: JSON.stringify(process.env.variable1),
},
})
);
// Return the modified config
return config;
},
};
- 在你的反应组件中,你可以像这样使用你的环境变量:
class HomePage extends React.Component {
constructor(props) {
this.state = {
env: { CUSTOM_VARIABLES }
}
logEnv() {
console.log(this.state.env.variable1)
}
}
显然,管理面板现在支持 dotenv 变量。
只需在您的 .env 变量前加上 STRAPI_ADMIN_ 前缀即可使用 process.env.
例如,.env 中的 STRAPI_ADMIN_KEY
可用作 process.env.STRAPI_ADMIN_KEY