值得注意的是,如果您将ProvidePlugin与externals属性结合使用,它将允许您jQuery传递到您的 webpack 模块闭包而无需显式地传递require它。这对于重构具有许多不同文件引用的遗留代码很有用$。
//webpack.config.js
module.exports = {
  entry: './index.js',
  output: { 
    filename: '[name].js' 
  },
  externals: {
    jquery: 'jQuery'
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
    })
  ]
};
现在在 index.js
console.log(typeof $ === 'function');
将有一个编译输出,如下所示传递给webpackBootstrap闭包:
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
    /* WEBPACK VAR INJECTION */(function($) {
        console.log(typeof $ === 'function');
    /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
    module.exports = jQuery;
/***/ }
/******/ ])
因此,您可以看到它$正在从 CDN 引用全局/窗口jQuery,但正在被传递到闭包中。我不确定这是预期的功能还是幸运的 hack,但它似乎对我的用例很有效。