代码之家  ›  专栏  ›  技术社区  ›  Franco

React/NPM在构建期间不遵守环境变量

  •  0
  • Franco  · 技术社区  · 7 年前

    我正在一个常量文件中设置环境,如下所示

    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;
    

    "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 使用 生产 应在何时使用环境 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)
      }
    });
    
    0 回复  |  直到 7 年前
        1
  •  1
  •   GProst    7 年前

    看不清你在用什么 API_URL 但我假设您只是在客户端代码中直接使用它。不管怎么说,我很确定问题出在哪里 -p

    和 争论是解决问题的捷径 --define process.env.NODE_ENV="production" 通过的论点 NODE_ENV=production 通过 DefinePlugin .

    顺便说一下,我不是100%确定,但我相信webpack不会自动通过 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"
    
    推荐文章