Defining Global Variables with Webpack
In your webpack configuration, you can use various methods to define global variables.
1. Modules
Create a module and export an object containing your global variables. Import this module and access the variables.
// config.js export default { FOO: 'bar', }; // somefile.js import CONFIG from './config.js'; console.log(`FOO: ${CONFIG.FOO}`);
2. ProvidePlugin
Use the ProvidePlugin to make a module available as a global variable. This plugin only includes the module in those modules where you use it.
// webpack.config.js const webpack = require('webpack'); const path = require('path'); module.exports = { plugins: [ new webpack.ProvidePlugin({ utils: 'utils', }), ], };
3. DefinePlugin
Use the DefinePlugin to define global constants as JSON strings.
// webpack.config.js const webpack = require('webpack'); module.exports = { plugins: [ new webpack.DefinePlugin({ PRODUCTION: JSON.stringify(true), VERSION: JSON.stringify('5fa3b9'), }), ], };
4. Global Object
Access the global object (window in browsers, global in Node) to define global variables.
// SPA or browser environment window.foo = 'bar'; // Webpack will convert global to window global.foo = 'bar';
5. Dotenv (Server Side)
Use the dotenv package to load environment variables from a .env file into Node's process.env.
// server.js require('dotenv').config(); const db = require('db'); db.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS, });
The above is the detailed content of How to Define Global Variables in Your Webpack Configuration?. For more information, please follow other related articles on the PHP Chinese website!