在构建过程中React / NPM不遵循环境变量

时间:2019-03-13 02:02:46

标签: reactjs npm webpack react-boilerplate

我正在像这样在常量文件中设置环境

const ENVIRONMENT = process.env.NODE_ENV;
const ENV_VARIABLES = {
  production: {
    API_URL: 'https://prod.myapi.com',
  },
  development: {
    API_URL: 'https://dev.myapi.com',
  },
  stage: {
    API_URL: 'https://stage.myapi.com/',

  }
};

export const API_URL = ENV_VARIABLES[ENVIRONMENT].API_URL;

我的package.json文件中包含以下命令

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress --hide-modules --display-optimization-bailout",
    "stage": "cross-env NODE_ENV=stage webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress --hide-modules --display-optimization-bailout",
    "start": "cross-env NODE_ENV=development node server",
  },

npm run build按预期使用production环境

npm start按预期使用development环境

npm run stage在应该使用舞台的production时使用API_URL环境。

编辑

我已将stage中的package.json更新为以下内容

"stage": "cross-env NODE_ENV=stage webpack --config internals/webpack/webpack.stage.babel.js --color -p --progress --hide-modules --display-optimization-bailout",

internals/webpack/webpack.stage.babel.js如下(长文件警告)。这和webpack.stage.babel.js之间的唯一区别是mode:none,这是在mode:production中设置为webpack.production.babel.js

// Important modules this config uses
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackPwaManifest = require('webpack-pwa-manifest');
// const OfflinePlugin = require('offline-plugin');
const { HashedModuleIdsPlugin } = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = require('./webpack.base.babel')({
  mode: 'none',

  // In production, we skip all hot-reloading stuff
  entry: [
    require.resolve('react-app-polyfill/ie11'),
    path.join(process.cwd(), 'app/app.js')
  ],

  // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
  output: {
    filename: '[name].[chunkhash].js',
    chunkFilename: '[name].[chunkhash].chunk.js'
  },

  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          warnings: false,
          compress: {
            comparisons: false
          },
          parse: {},
          mangle: true,
          output: {
            comments: false,
            ascii_only: true
          }
        },
        parallel: true,
        cache: true,
        sourceMap: true
      })
    ],
    sideEffects: true,
    concatenateModules: true,
    splitChunks: {
      chunks: 'all',
      minSize: 30000,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      name: true,
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'all'
        },
        main: {
          chunks: 'all',
          minChunks: 2,
          reuseExistingChunk: true,
          enforce: true
        }
      }
    },
    runtimeChunk: true
  },

  plugins: [
    // Minify and optimize the index.html
    new HtmlWebpackPlugin({
      template: 'app/index.html',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true
      },
      inject: true
    }),

    // Put it in the end to capture all the HtmlWebpackPlugin's
    // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
    /*new OfflinePlugin({
      relativePaths: false,
      publicPath: '/',
      appShell: '/',

      // No need to cache .htaccess. See http://mxs.is/googmp,
      // this is applied before any match in `caches` section
      excludes: ['.htaccess'],

      caches: {
        main: [':rest:'],

        // All chunks marked as `additional`, loaded after main section
        // and do not prevent SW to install. Change to `optional` if
        // do not want them to be preloaded at all (cached only when first loaded)
        additional: ['*.chunk.js']
      },

      // Removes warning for about `additional` section usage
      safeToUseOptionalCaches: true
    }),*/

    new CompressionPlugin({
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    }),

    new WebpackPwaManifest({
      name: 'React Boilerplate',
      short_name: 'React BP',
      description: 'My React Boilerplate-based project!',
      background_color: '#fafafa',
      theme_color: '#b1624d',
      inject: true,
      ios: true,
      icons: [
        {
          src: path.resolve('app/images/icon-512x512.png'),
          sizes: [72, 96, 128, 144, 192, 384, 512]
        },
        {
          src: path.resolve('app/images/icon-512x512.png'),
          sizes: [120, 152, 167, 180],
          ios: true
        }
      ]
    }),

    new HashedModuleIdsPlugin({
      hashFunction: 'sha256',
      hashDigest: 'hex',
      hashDigestLength: 20
    })
  ],

  performance: {
    assetFilter: assetFilename =>
      !/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)
  }
});

1 个答案:

答案 0 :(得分:1)

无法真正看到您在API_URL中使用的位置,但是我认为您只是在客户端代码中直接使用它。无论如何,我很确定问题出在传递到Webpack的-p参数中。在应用该参数之前,您应该阅读一下该参数的含义。

-p参数是--define process.env.NODE_ENV="production"参数的快捷方式,它通过DefinePluginNODE_ENV=production传递到构建运行时。

顺便说一下,我不确定100%,但是我相信webpack不会自动将NODE_ENV env变量传递到编译运行时,所以除非您已经这样做了(因为我不这样做)在您提供的配置中看到它)我相信您应该将NODE_ENV传递给编译运行时,如下所示:

new webpack.DefinePlugin({
  // it's important to use JSON.stringify here in order to escape quotes
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})

或使用CLI参数:

--define process.env.NODE_ENV="staging"