【发布时间】:2015-05-12 06:04:59
【问题描述】:
我在我的应用程序中使用 Webpack,我在其中创建了两个入口点 - bundle.js 用于我的所有 JavaScript 文件/代码,以及 vendor.js 用于所有库,如 jQuery 和 React。为了使用以 jQuery 作为其依赖项的插件并且我希望它们也包含在 vendor.js 中,我该怎么做?如果这些插件有多个依赖项怎么办?
目前我正在尝试在这里使用这个 jQuery 插件 - https://github.com/mbklein/jquery-elastic。 Webpack 文档提到了providePlugin 和 imports-loader。我使用了providePlugin,但jQuery 对象仍然不可用。这是我的 webpack.config.js 的样子-
var webpack = require('webpack');
var bower_dir = __dirname + '/bower_components';
var node_dir = __dirname + '/node_modules';
var lib_dir = __dirname + '/public/js/libs';
var config = {
addVendor: function (name, path) {
this.resolve.alias[name] = path;
this.module.noParse.push(new RegExp(path));
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jQuery",
"window.jQuery": "jquery"
}),
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
],
entry: {
app: ['./public/js/main.js'],
vendors: ['react','jquery']
},
resolve: {
alias: {
'jquery': node_dir + '/jquery/dist/jquery.js',
'jquery.elastic': lib_dir + '/jquery.elastic.source.js'
}
},
output: {
path: './public/js',
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader' },
{ test: /\.jquery.elastic.js$/, loader: 'imports-loader' }
]
}
};
config.addVendor('react', bower_dir + '/react/react.min.js');
config.addVendor('jquery', node_dir + '/jquery/dist/jquery.js');
config.addVendor('jquery.elastic', lib_dir +'/jquery.elastic.source.js');
module.exports = config;
但尽管如此,它仍然在浏览器控制台中抛出错误:
Uncaught ReferenceError: jQuery is not defined
同样,当我使用imports-loader时,它会抛出一个错误,
要求未定义'
在这一行:
var jQuery = require("jquery")
但是,当我不将它添加到我的 vendor.js 文件时,我可以使用相同的插件,而是以正常的 AMD 方式需要它,就像我如何包含我的其他 JavaScript 代码文件一样 -
define(
[
'jquery',
'react',
'../../common-functions',
'../../libs/jquery.elastic.source'
],function($,React,commonFunctions){
$("#myInput").elastic() //It works
});
但这不是我想要做的,因为这意味着 jquery.elastic.source.js 与我的 JavaScript 代码捆绑在 bundle.js 中,我希望我的所有 jQuery 插件都在供应商中。 js 捆绑包。那么我该如何实现呢?
【问题讨论】:
-
不确定这是否是您的问题,但您肯定需要将 windows.jQuery 更改为 "window.jQuery": "jquery" 。 webpack 的网站上有一个错字,我假设你是从那里得到的代码。
-
@AlexHawkins 哦,是的,我注意到并修复了它。感谢您指出!
标签: javascript jquery amd webpack