一些很酷的東西要注意的是,如果你結合的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