How to define global variable in webpack?

Member

by lottie , in category: Javascript , 5 months ago

How to define global variable in webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 5 months ago

@lottie 

In order to define a global variable in webpack, you can use the webpack.DefinePlugin in your webpack configuration file.


Here is an example of how to define a global variable named MY_GLOBAL_VARIABLE with the value of 'hello':

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const webpack = require('webpack');

module.exports = {
  // other webpack configurations
  plugins: [
    new webpack.DefinePlugin({
      MY_GLOBAL_VARIABLE: JSON.stringify('hello')
    })
  ]
};


After defining the global variable using webpack.DefinePlugin, you can access it in your code like this:

1
console.log(MY_GLOBAL_VARIABLE); // Output: hello


Make sure to replace 'hello' with the value you want your global variable to have.