我在应用程序中使用Webpack,在其中创建两个入口点-所有我的JavaScript文件/代码的bundle.js,以及所有库(如jQuery和React)的vendor.js。为了使用以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;
但是尽管如此,它仍然在浏览器控制台中引发错误:
未捕获的ReferenceError:未定义jQuery
Similarly, when I use the imports-loader, it throws an error,
require is not defined'
in this line:
var jQuery = require("jquery")
However, I could use the same plugin when I don't add it to my vendors.js file and instead required it in the normal AMD way as how I include my other JavaScript code files, like-
define(
[
'jquery',
'react',
'../../common-functions',
'../../libs/jquery.elastic.source'
],function($,React,commonFunctions){
$("#myInput").elastic() //It works
});
But this is not what I want to do, as this would mean that jquery.elastic.source.js is bundled along with my JavaScript code in bundle.js, and I want all my jQuery plugins to be in the vendors.js bundle. So how do I go about achieving this?
编辑:有时您只想将webpack用作简单Web项目的模块捆绑器-保持自己的代码井井有条。以下解决方案适用于那些只希望外部库在其模块中按预期方式工作的人,而又无需花费大量时间来研究webpack设置。(在-1之后编辑)
快速简便的解决方案(es6),如果您仍在挣扎或希望避免使用外部配置/其他webpack插件配置:
在模块内部: