env.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * 加载.env*环境变量文件,用于将定义的环境变量注入DefinePlugin
  3. */
  4. const fs = require('fs');
  5. const path = require('path');
  6. const paths = require('./paths');
  7. // 确保在env.js之后包含paths.js,以便读取.env变量
  8. delete require.cache[require.resolve('./paths')];
  9. const { NODE_ENV } = process.env;
  10. if (!NODE_ENV) {
  11. throw new Error('Node的环境变量“NODE_ENV”未定义!');
  12. }
  13. const dotenvFiles = [
  14. `${paths.dotenv}.${NODE_ENV}.local`,
  15. `${paths.dotenv}.${NODE_ENV}`,
  16. NODE_ENV !== 'test' && `${paths.dotenv}.local`,
  17. paths.dotenv,
  18. ].filter(Boolean);
  19. // 从.env*文件中加载环境变量
  20. /* eslint-disable import/no-extraneous-dependencies */
  21. dotenvFiles.forEach(dotenvFile => {
  22. if (fs.existsSync(dotenvFile)) {
  23. require('dotenv-expand')(
  24. require('dotenv').config({
  25. path: dotenvFile,
  26. })
  27. );
  28. }
  29. });
  30. const appDirectory = fs.realpathSync(process.cwd());
  31. process.env.NODE_PATH = (process.env.NODE_PATH || '')
  32. .split(path.delimiter)
  33. .filter(folder => folder && !path.isAbsolute(folder))
  34. .map(folder => path.resolve(appDirectory, folder))
  35. .join(path.delimiter);
  36. const SETTING = /^_SETTING_/i;
  37. function getClientEnvironment(publicUrl) {
  38. /* eslint-disable no-param-reassign */
  39. const raw = Object.keys(process.env)
  40. .filter(key => SETTING.test(key))
  41. .reduce(
  42. (env, key) => {
  43. const newKey = key.substr(9);
  44. env[newKey] = process.env[key];
  45. return env;
  46. },
  47. {
  48. NODE_ENV: process.env.NODE_ENV || 'development',
  49. PUBLIC_URL: publicUrl,
  50. }
  51. );
  52. // 将所有变量值进行字符串化,以便传入DefinePlugin插件
  53. /* eslint-disable no-param-reassign */
  54. const stringified = {
  55. 'process.env': Object.keys(raw).reduce((env, key) => {
  56. env[key] = JSON.stringify(raw[key]);
  57. return env;
  58. }, {}),
  59. };
  60. return { raw, stringified };
  61. }
  62. module.exports = getClientEnvironment;