Define global variable with webpack

后端 未结 5 1754
臣服心动
臣服心动 2020-11-22 11:16

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

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:51

    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.

提交回复
热议问题