1

I am setting the Environment in a constants file like so

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;

My package.json file has the following commands in it

"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 uses the production environment as expected

npm start uses the development environment as expected

npm run stage uses the production environment when it should be using API_URL of stage.

EDIT

I've updated stage in package.json to the following

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

and internals/webpack/webpack.stage.babel.js is as follows (long file warning). The only difference between this one and webpack.stage.babel.js is mode:none, this is setup to mode:production in 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)
  }
});
Franco
  • 2,846
  • 7
  • 35
  • 54

1 Answers1

1

Can't really see where you're using API_URL but I assume you're just using it directly in the client code. Anyway, I'm pretty sure that the problem is in -p argument that you pass to a webpack. You should read about what which argument means before you apply it.

And -p argument is a shortcut for --define process.env.NODE_ENV="production" argument which passes NODE_ENV=production to the build runtime via DefinePlugin.

By the way, I'm not 100% sure, but I believe webpack doesn't automatically pass NODE_ENV env variable into the compilation runtime, so unless you're already doing it (cause I don't see it in the provided config of yours) I believe you should pass the NODE_ENV to the compilation runtime as follows:

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)
})

Or using the CLI argument:

--define process.env.NODE_ENV="staging"
GProst
  • 9,229
  • 3
  • 25
  • 47