Define global variable with webpack

webpack define plugin
webpack provideplugin
webpack externals
webpack librarytarget
webpack exports-loader
webpack script-loader
webpack polyfill
webpack window is not defined

Is it possible to define a global variable with webpack to result something like this:

var myvar = {};

All of the examples I saw were using external file require("imports?$=jquery!./file.js")


There are several way to approach globals:

1) Put your variables in a module.

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

2) Webpack's ProvidePlugin

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.

3) Use Webpack's DefinePlugin

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

Use it like:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
4) Use the global window object (or Node's global)
window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

5) Use a package like dotenv

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})
Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

Shimming, Let's start with the first use case of shimming global variables. cases, it could help to force the CommonJS path by setting define=>false via the imports-loader . Webpack is modular bundler. Webpack can take care of bundling alongside a separate task runner. Webpack can take care of bundling alongside a separate task runner.


I was about to ask the very same question. After searching a bit further and decyphering part of webpack's documentation I think that what you want is the output.library and output.libraryTarget in the webpack.config.js file.

For example:

js/index.js:

var foo = 3;
var bar = true;

webpack.config.js

module.exports = {
   ...
   entry: './js/index.js',
   output: {
      path: './www/js/',
      filename: 'index.js',
      library: 'myLibrary',
      libraryTarget: 'var'
   ...
}

Now if you link the generated www/js/index.js file in a html script tag you can access to myLibrary.foo from anywhere in your other scripts.

Module Variables, Defines the value that will be returned when a consumer makes a require call to the module This variable is equal to the default value of module.exports (i.e. an object). Can be used to do cool stuff with a global require function if available. I’m building an alternative to webpack-dev-server which takes the url as an option rather than as a string added to the entry file value. The url is injected into the client using the DefinePlugin. The plugin allows for HMR in node & web if anyone is interested.


Use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

new webpack.DefinePlugin(definitions)
Example:
plugins: [
  new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true)
  })
  //...
]
Usage:
console.log(`Environment is in production: ${PRODUCTION}`);

how to define a global variable? · Issue #1236 · webpack/webpack , It tries to replace all the occurrences of the variable "name". How to declare a global variable without loading a file in Webpack 2? Basically bundle whatever is consuming this variable. – lorefnon Aug 2 '17 at 20:28 I do bundle together the file that defines this variable and the files that use it, all of them. But the function definition still remains invisible to the function implementation.


You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Expose Global Variables, Methods, and Modules in JavaScript , Expose Global Variables, Methods, and Modules in JavaScript. Furthermore, a setup to expose methods and modules with Webpack is presented. in the developer console in Chrome it should show the function definition. webpack's environment variables are different from the environment variables of operating system shells like bash and CMD.exe The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack.config.js.


I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

A Guide to inject variable into your code using webpack, We are going to use DefinePlugin, included with Webpack to define the global variable and inject them into our code. Using the NPM scripts we can pass the  var g = window || global; g['v'] = 3; I understand the concept of modules and don't use globals in my applications. However, having global variables during debugging in the console may be beneficial, especially when using bundlers like Webpack instead of loaders like SystemJs where you can easily import a module in a console.


Why are global vars undefined when using module.exports , I've implemented it, (Webpack is combining the two files into a bundle.js) In particular a global variable defined in my main app.js file (kinda  For our example we want to define 2 global constants; a string called __VERSION__ and a boolean called __IN_DEBUG__. The names are deliberately wacky to draw attention to the fact that these are not your everyday, common-or-garden variables. Them's "special".


How to create a global variable with webpack from a module?, application with ecma6 and trying to create global variables using webpack. displays undefined. should show the global module defined in the webpack. webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.


Importing External Libraries & Global Variables > Webpack Encore , Global Variables inside Webpack. Cool! We've imported jQuery in app.js and set it to a $ variable. And because that <script> tag is included above our inline  __webpack_hash__ (webpack-specific) This variable is only available with the HotModuleReplacementPlugin or the ExtendedAPIPlugin . It provides access to the hash of the compilation.