In the vue CLI official documentation, environment variables in the. Env file can only be used in front-end files if they start with VUE_APP_. Is there any way to overcome this limitation? That must be arranged.

Looking at the Webpack configuration file with the vue inspect command, we found that it actually works by injecting environment variables through webPack’s DefinePlugin:

/* config.plugin('define') */
new DefinePlugin(
  {
    'process.env': {
      VUE_APP_TITLE: '"LEMON TREE"'.NODE_ENV: '"development"'.BASE_URL: '" "'}})Copy the code

The plugin is named define in the vue CLI, which can be easily overridden by the chainWebpack(config) {} function in vue.config.js.

To inject environment variables, we need to read the contents of the.env file. We can directly use the mature dotenv library to do this. The key implementation code is as follows:

const dotEnv = require('dotenv');

const config = {
	/ * * *@see https://github.com/neutrinojs/webpack-chain
	 **/
	chainWebpack(config) {
		// Handle environment variables
		const baseEnv = dotEnv.config().parsed;
		const modeEnv = dotEnv.config({
			path: path.resolve(__dirname, `.env.${ process.env.NODE_ENV }`),
		}).parsed;
		Object.assign(baseEnv, modeEnv);
		// I will filter out environment variables starting with WD_ for separate injection, you can adjust the logic according to the actual situation
		const targetEnv = Object.keys(baseEnv).filter(key= > key.startsWith('WD_')).reduce((env, key) = > {
			env[key] = baseEnv[key];
			return env;
		}, {});
		// Modify the plug-in call parameters
		config.plugin('define').tap(args= > {
			let arg = args[0];
			Object.assign(arg['process.env'], targetEnv);
			returnargs; }); }};exports = module.exports = config;
Copy the code

Webpack-chain encapsulation of webpack configuration is really nice~, modify very elegant, through the above method can be very convenient to customize the injection rules of environment variables.