How to use expose-Loader to solve plug-in dependencies of third-party libraries

Bootstrap. js, which only allows jQuery to be exposed as a global variable, causes some plugin issues that don’t support commonJs to expose.

This is the beginning of the bootstrap source code.

    if (typeof jQuery === 'undefined') {
      throw new Error('Bootstrap\'s JavaScript requires jQuery')
    }Copy the code

After a series of searches, some answers came up, some saying you can configure the externals attribute in Webpack. As follows:

module.exports = {
    // ...
    externals: {
        jquery: 'jQuery'
    }
    // ...
};Copy the code

Var jquery = require(‘jquery’); Use script global inclusion for static files. Of course we can introduce other plug-ins at the same time.

<script src='jquery.js'></script>
<script src='bootstrap.js'></script>    Copy the code

But that’s not where we want to end up. We want to use require to bring in the JS library, and finally get to compile them. Expose-loader gives us this functionality.

NPM install jquery –save NPM install bootstrap –save

Install expose – loader

npm install expose-loader --save-dev

Modify the webpack. Config. Js

Module. exports = {loaders: [{// get jquery module's path test: require.resolve('jquery'), // bind jquery to window. jquery loader: 'expose?jQuery' }] };Copy the code

Ps: If you want a module to have multiple injected global variables, you need the following configuration

Module. exports = {loaders: [{// get jquery module's absolute path test: Resolve ('jquery'), // bind jquery to window. jquery and window. expose: 'jquery! Expose?Copy the code

Finally, use it in main.js

    var jquery = require('jquery');
    // 插件注入jquery
    require('bootstrap');   Copy the code

If you use the Expose loader in JS

Var jquery = require("expose? jQuery! jquery");Copy the code