Skip to content

webpack config file preload all different environment configs. #1004

@leaveswoods

Description

@leaveswoods

Enhancement

Reason to enhance/problem with existing solution
webpack/webpack.config.ts preload all different environment configs that may result in running unintended code.

For example, our team uses dotenv-webpack for injecting env variables during the build process.

We enable a safe check with .env.example to ensure env variables are all set. Since this is done whenever we load webpack plugin config, so we need to make sure only the desired webpack config is loaded, otherwise, we will get a warning or build failed because the production plugin config is also loaded in local development environment and apparently we don't have .prod.env in local(unless we make a fake one to fix this issue)

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: './server/.dev.env'
      safe: './server/.env.example', // load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
    })
  ]
  ...
};

Suggested enhancement
I already fixed this for my team couple months ago. But I didn't realize we are actually using reactGo as project starter, which was setup 2 years ago. For fixing that, I just change all config render variables to functions, and use ifs to make sure we only generate the desired webpack config each time.

Like so

const prodServerRender = () => {
...
}
const prodBrowserRender = () =>  {
...
}
const devBrowserRender = () => {
...
}
const devServerRender =  () => {
}

if (isBrowser && isProduction) {
  return prodBrowserRender()
} else if (isBrowser && !isProduction) {
  return devBrowserRender()
} else if (!isBrowser && isProduction) {
  return prodServerRender()
} else if (!isBrowser && !isProduction) {
  return devServerRender()
} else {
  throw new Error('Unknown webpack config.')
}

Pros
Won't preload all configs, and only generate desired webpack config each time,
Cons
looks a bit clutter, but need very little maintenance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions