This article mainly introduces the sample code of Webpack server-side code packaging. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Environment variables
Before, we would often use process.env.NODE_ENV in the project, but this variable is Webpack packaging has an impact and is optimized during production.
So, we will use other environment variables to distinguish:
new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"', 'process.env.API_ENV': `"${process.env.API_ENV || 'development'}"` })
Like this, NODE_ENV is always production.
And our actual development/product environment uses the process.env.API_ENV variable (because the project is a koa interface service project, so it is named this way and can be changed. It can be arbitrary, as long as you are happy).
Dynamic configuration packaging
Note
We used to use node.js In back-end projects, dynamic configuration loading is generally written like this:
const ENV = process.env.NODE_ENV || 'development'; // eslint-disable-next-line import/no-dynamic-require const options = require(`./_${ENV}`); module.exports = options;
In order to improve readability and possible reuse of ENV, we will define a separate variable.
If you do this directly in a webpack packaged project, it will cause a problem. For example, I now have multiple configurations:
_development.js
_test.js
_production.js
_staging.js
Even if the current environment I pass in is development, all configuration files will still be packaged (but will never be executed). In this case, there is a risk of sensitive information being leaked.
Correct The posture should be like this:
config/index.js
##
// eslint-disable-next-line import/no-dynamic-require const options = require(`./_${process.env.API_ENV || 'development'}`); module.exports = options;
Modular packaging
// config/_development.js exports.enabledModules = ['user', 'demo']; // 可能 src 目录下 还有其他模块目录, 如 'manage' 等
// src/server.js // 动态加载启用的模块 enabledModules.forEach((mod) => { /* eslint-disable global-require,import/no-dynamic-require */ const routes = require(`./${mod}/route`); routes.middleware() |> app.use; });
Advanced use
Compress the code and add source-map support
The above is the detailed content of Webpack server-side code packaging. For more information, please follow other related articles on the PHP Chinese website!