@lottie
In webpack, global variables can be defined by using the DefinePlugin
to replace occurrences of specified placeholders with their corresponding values. Here's how you can define global variables in webpack:
1
|
npm install webpack webpack-cli --save-dev |
1 2 3 4 5 6 7 8 9 10 11 12 |
const webpack = require('webpack'); module.exports = { // Other webpack configuration options plugins: [ new webpack.DefinePlugin({ MY_GLOBAL_VAR: JSON.stringify('my global variable value'), ANOTHER_GLOBAL_VAR: JSON.stringify('another global variable value') }) ] }; |
In the above code snippet, we define two global variables MY_GLOBAL_VAR
and ANOTHER_GLOBAL_VAR
with their respective values.
1 2 |
console.log(MY_GLOBAL_VAR); // Output: 'my global variable value' console.log(ANOTHER_GLOBAL_VAR); // Output: 'another global variable value' |
When webpack bundles your code, it will replace occurrences of MY_GLOBAL_VAR
and ANOTHER_GLOBAL_VAR
with their corresponding values at build time.
1
|
npx webpack --config webpack.config.js |
This will generate a bundled file with your global variables defined in it.
By using the DefinePlugin
, you can easily define and use global variables in webpack configurations.