13

Let I have a file index.js with content

var a = 1;

I have index.html file which include index.js using <script> tag. When I open index.html page in browser, then the a variable can be accessed directly in browser console. Because a have global scope and it is global variable.

Now I am using npm and webpack. My package.json file content is

"scripts": {
  "build": "webpack"
},

and webpack.config.js file content is

module.exports = {
entry: './index.js',
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
}

Now I run npm build then new file is created in dist folder named bundle.js.

Now I replace index.js from script tag of index.html file with dist/bundle.js .

Now I run index.html in browser, but variable a is no longer access in browser console directly. It is not a global variable now.

My question is : Is there a way by which we can access variable a globally just like we access initially?

I have not found exact answer on internet. I found a loader expose-loader but it also can't solve my problem.

8
  • 1
    what do you need the global var for ? I mean what is the use case? Commented Jul 15, 2018 at 19:44
  • 1
    Possible duplicate of Define global variable with webpack Commented Jul 16, 2018 at 0:21
  • @Luillyfe I have old writtten many js file for a website which are included in html by script tag. Many function and variable are globally define, so that they can access by other included javascript file. Commented Jul 16, 2018 at 6:51
  • Buy after the build what you need for ? Before the build you can still access the var, Right? Commented Jul 16, 2018 at 7:07
  • @Luillyfe I want to minify js file by using UglifyJsPlugin Commented Jul 16, 2018 at 7:47

1 Answer 1

12

When webpack bundles your javascript it wraps all of your individual files/modules in functions so they are no longer run in the global scope, therefore if you want to make a variable global you have to explicitly set it on the window object, i.e.

window.a = 1;

This will make a accessible from the browser console in index.html.

Sign up to request clarification or add additional context in comments.

2 Comments

I have many variable and functions defined globally in many files. By this way I have to change at many places of all javascript file. Is there any simple way
Don't know why I didn't think of this. 🤦‍♂️ Sometimes the best answers are the simplest and most obvious. Thank you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.