如何使“require('jquery')”自动加载webpack中的许多jquery插件/扩展?
有一些我想jQuery自动拥有的插件。 在一个常规的网站,我只是简单地包括jQuery和脚本。 我如何用webpack来完成这个任务? 假设没有插件的npm包,我只是想从文件中加载它们。
我将假定以下目录结构:
项目 | - 应用程序 | | - 供应商 | | | - 插件 | | | | - plugin-1.js | | | | - plugin-2.js | | | | - ... | | | | | | - jquery.js | | | | - jquery-with-plugins.js | | - main.js | | - js | | - bundle.js | | - webpack.config.js | - package.json ...
这里是关键文件的内容:
// app/jquery-with-plugins.js require('vendor/jquery'); req = require.context('vendor/plugins', true, /\.js$/); req.keys().forEach(function (plugin) { req(plugin); }); module.exports = jQuery; // app/main.js var $ = require('jquery'); $(function () { $('.selector-1').use_plugin_1(); $('.selector-2').use_plugin_2(); }); // webpack.config.js var path = require('path'); module.exports = { context: path.join(__dirname, 'app'), entry: './main', output: { path: path.join(__dirname, 'js'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, include: [ path.join(__dirname, 'app/vendor') ], loader: 'script' } ] }, resolve: { alias: { 'jquery$': path.join(__dirname, 'app/jquery_with_plugins'), 'vendor': path.join(__dirname, 'app/vendor') } }, extensions: ['', '.js'] }; // package.json { "name": "temp", "version": "0.0.0", "private": true, "scripts": { "build": "webpack --progress --colors" }, "devDependencies": { "node-libs-browser": "^0.5.0", "script-loader": "^0.6.1", "webpack": "^1.9.4" } }
app/vendor
目录中的每个JavaScript文件都被configuration为使用脚本加载器加载 ,因此将在全局上下文中执行。 在app/jquery-with-plugins.js
我首先加载jQuery
,然后加载每个插件,以便导出jQuery
( 注意,我不必导出jQuery
因为它已经全局公开,但我认为最好使用CommonJS模块这里出)。每个插件将已经附加到jQuery对象。
我已经别名jquery
引用app/jquery-with-plugins.js
(请参阅resolve.alias
configuration),因此我可以通过简单地执行require('jquery')
来要求带有所有插件require('jquery')
。 更妙的是,为了能够添加插件并立即使用,只需将其添加到app/vendor/plugins
。 app/main.js
显示了一个例子
最后,通过运行npm run build
,所有东西都可以绑定到js/bundle.js
。