Initializing third-part plugin in webpack bundle.j

2019-09-09 19:59发布

One of my module is external plugin (WOW effect), which needs to be initialize in index.html to works properly by using:

<script>
new WOW().init();
</script>

If I use the plugin as a completely external file - it works. But when I compile it with webpack it gives me an error:

Uncaught ReferenceError: wow is not defined.

My config file looks like this:

module.exports = {
    entry: './modules/_entry.js',
    output: {
        filename: 'bundle.js'
    }
};

and _entry.js contains:

require("./wow.js");

What I am doing wrong?

1条回答
The star\"
2楼-- · 2019-09-09 20:24

There are two possibilities:


  1. Externals The benefit of this one is that you can easly exchange your local script file for example for a CDN one. In this method, the source of the script is an external vendor file.

    • Have a folder with you vendor scripts, like WOW.
    • Link to it in your HTML file using <script src="vendors/WOW.js">.
    • You are free to make the initialization like you indicated above, inside another <script> tag.
    • Add externals configuration to your webpack config:

var config = {
  entry: [...],
  output: {...},
  externals: {
    Wow: 'WOW'
  },
  module: {...},
  plugins: [...]
};

  • From now on, you have access to an artificial module Wow in all your application modules and you can import or require them (although in case of WOW, I don't think you would need it).

  1. Expose-loader This way lets you move to the global scope modules that you would normally use as... well, modules :) In this method, the source of the script is a module (either yours own, or installed with npm).

    • Install the plugin: npm install expose-loader --save-dev
    • Add the expose loader configuration to your webpack config file:

var config = {
  entry: [...],
  output: {...},
  module: {
    loaders: [{
      ...
    }, {
      test: 'path/to/your/module/wow.min.js',
      loader: "expose?WOW"
    }]
  },
  plugins: [...]
};

  • This should make the WOW a global variable, usable inside <script> tags.
查看更多
登录 后发表回答