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")
This question is related to
javascript
webpack
webpack-2
webpack-3
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.
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 = {};
Use DefinePlugin.
The DefinePlugin allows you to create global constants which can be configured at compile time.
new webpack.DefinePlugin(definitions)
plugins: [
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true)
})
//...
]
console.log(`Environment is in production: ${PRODUCTION}`);
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
Source: Stackoverflow.com