一些很酷的东西要注意的是,如果你结合的externals
财产使用ProvidePlugin
它可以让你有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
,但正在传递给闭包。我不确定这是否是预期的功能或幸运的黑客攻击,但它似乎对我的使用情况很好。
应该在'webpack.ProvidePlugin'之前加'new' http://webpack.github.io/docs/list-of-plugins.html –
是的,谢谢。我修复了它。 –
为什么不使用脚本加载器?这很容易,就像@dtothefp解释过的 – timaschew