Can I use an ES6/2015 module import to set a reference in 'global' scope?

前端 未结 6 1174
温柔的废话
温柔的废话 2021-01-31 03:22

I have this situation where I am trying to import an existing library, which I\'ll call troublesome (using Webpack/Babel FWIW) and it has a global reference to

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 03:44

    Shimming modules is the way to go: http://webpack.github.io/docs/shimming-modules.html

    I quote from the page:

    plugin ProvidePlugin

    This plugin makes a module available as variable in every module. The module is required only if you use the variable.

    Example: Make $ and jQuery available in every module without writing require("jquery").

    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    })
    

    To use this with your webpack-config just add this object to an array called plugins in the config:

    // the plugins we want to use 
    var plugins = [
       new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery",
          "window.jQuery": "jquery"
       })
    ];
    
    // this is your webpack-config
    module.exports = {
        entry: ...,
        output: ...,
        module: ...,
        plugins: plugins
    }
    

提交回复
热议问题