/** * 加载.env*环境变量文件,用于将定义的环境变量注入DefinePlugin */ const fs = require('fs'); const path = require('path'); const paths = require('./paths'); // 确保在env.js之后包含paths.js,以便读取.env变量 delete require.cache[require.resolve('./paths')]; const { NODE_ENV } = process.env; if (!NODE_ENV) { throw new Error('Node的环境变量“NODE_ENV”未定义!'); } const dotenvFiles = [ `${paths.dotenv}.${NODE_ENV}.local`, `${paths.dotenv}.${NODE_ENV}`, NODE_ENV !== 'test' && `${paths.dotenv}.local`, paths.dotenv, ].filter(Boolean); // 从.env*文件中加载环境变量 /* eslint-disable import/no-extraneous-dependencies */ dotenvFiles.forEach(dotenvFile => { if (fs.existsSync(dotenvFile)) { require('dotenv-expand')( require('dotenv').config({ path: dotenvFile, }) ); } }); const appDirectory = fs.realpathSync(process.cwd()); process.env.NODE_PATH = (process.env.NODE_PATH || '') .split(path.delimiter) .filter(folder => folder && !path.isAbsolute(folder)) .map(folder => path.resolve(appDirectory, folder)) .join(path.delimiter); const SETTING = /^_SETTING_/i; function getClientEnvironment(publicUrl) { /* eslint-disable no-param-reassign */ const raw = Object.keys(process.env) .filter(key => SETTING.test(key)) .reduce( (env, key) => { const newKey = key.substr(9); env[newKey] = process.env[key]; return env; }, { NODE_ENV: process.env.NODE_ENV || 'development', PUBLIC_URL: publicUrl, } ); // 将所有变量值进行字符串化,以便传入DefinePlugin插件 /* eslint-disable no-param-reassign */ const stringified = { 'process.env': Object.keys(raw).reduce((env, key) => { env[key] = JSON.stringify(raw[key]); return env; }, {}), }; return { raw, stringified }; } module.exports = getClientEnvironment;