这种问题大多出现在自建webpack配置时,未安装dotenv-webpack包所致
npm i dotenv-webpack --save-dev
// .env
DB_HOST=127.0.0.1
DB_PASSWORD=test1233
DB_USER=user1
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
console.log(process.env.DB_HOST);
//127.0.0.1
另外dotenv给出了一些配置项
new Dotenv({
path: isProd ? 'env.production' : 'env.development', // load this now instead of the ones in '.env'
safe: true, // load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
allowEmptyValues: true, // allow empty variables (e.g. `FOO=`) (treat it as empty string, rather than missing)
systemvars: true, // load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
silent: true, // hide any errors
defaults: false, // load '.env.defaults' as the default values if empty.
//prefix: 'ggw', // reference your env variables as 'import.meta.env.ENV_VAR'.
/*
* 默认为process.env.xxxx,如果修改了prefix,如ggw,那么使用时就要写成ggwxxxx
* 如修改为ggw.,那么使用时就要写成ggw.xxxx
*/
}),
path路径其实可以自定义,对应的文件名也可以自定义