Description of actual project requirements

Get the current environment at run time (production or development) and do different things

Examples of actual project requirements

if(__env__) {
// do something
} else {
// do something
}
Copy the code

Rollup

**:**

  • To do this, we need to find a “portal” to distinguish between our environments, which we can do through NPM script, because we need to execute different NPM scripts to build our projects in development and production environments.
  • Rollup can mount properties to process.env in NPM script with the –environment argument

example

package.json

{/ /... "scripts": { "build": "rollup -c --environment ENV:production", "env": "rollup -c --environment ENV:development" } // ... }Copy the code

rollup.config.js

Import replace from '@rollup/plugin-replace'; import replace from '@rollup/plugin-replace'; export default { // ... Plugins: [replace({__env__: json.stringify (process.env.env)})] // plugins: [replace({__env__: json.stringify (process.env.env)) // };Copy the code

Actual business code snippets

// Declare var __env__: string; // Declare var __env__: string; console.info(__env__);Copy the code

By doing so, the __env__ variable can be compiled to “development” or “production” by rollup

Implemented via Webpack

**:**

  • Rollup is a rollup implementation, but the build file is different

example

package.json

// Same as package.json aboveCopy the code

webpack.config.js

const { DefinePlugin } = require('webpack'); Module.exports = (env) => {// exports = (env) => {// exports = (env) Plugins: [new DefinePlugin({__env__: json.stringify (env.env) // here via webpack inject env variable})]}}Copy the code

Actual business code snippets

// Same as aboveCopy the code

Pay attention to the point

Webpack and rollup both use character substitution at compile time to replace __env__ with the corresponding value, so make sure __env__ does not have the same name as normal code. I won’t give you any examples here, but you can implement the above method, and then run a counter example to see the effect.

tree shaking

Tree shaking is enabled by default for Webpack and Rollup, and as long as code has no side effects, branch judging statements and environment variables will make it "useless", as shown in the screenshot below after rollup packagingCopy the code

Before packaging

After packaging

If you have time, update how this works with vue and React scaffolding.