Managing jQuery plugin dependency in webpack

前端 未结 11 1522
陌清茗
陌清茗 2020-11-22 01:17

I\'m using Webpack in my application, in which I create two entry points - bundle.js for all my JavaScript files/codes, and vendors.js for all libraries like jQuery and Reac

11条回答
  •  感动是毒
    2020-11-22 01:33

    I got things working nicely while exposing $ and jQuery as global variables with Webpack 3.8.1 and the following.

    Install jQuery as a project dependency. You can omit @3.2.1 to install the latest version or specify another version.

    npm install --save jquery@3.2.1
    

    Install expose-loader as a development dependency if not installed already.

    npm install expose-loader --save-dev
    

    Configure Webpack to load and expose jQuery for us.

    // webpack.config.js
    const webpack = require('webpack')
    
    module.exports = {
      entry: [
        // entry bits
      ],
      output: {
        // output bits
      },
      module: {
        rules: [
          // any other rules
          {
            // Exposes jQuery for use outside Webpack build
            test: require.resolve('jquery'),
            use: [{
              loader: 'expose-loader',
              options: 'jQuery'
            },{
              loader: 'expose-loader',
              options: '$'
            }]
          }
        ]
      },
      plugins: [
        // Provides jQuery for other JS bundled with Webpack
        new webpack.ProvidePlugin({
          $: 'jquery',
          jQuery: 'jquery'
        })
      ]
    }
    

提交回复
热议问题