[英]jQuery and webpack: how to require
我知道有关此问题的stackoverflow有几个类似的问题,但我已经关注了很多这些问题,但他们只是部分帮助了。
我正在尝试使用webpack在我的Angular应用程序中使用jQuery。 但是,浏览器抱怨没有找到jQuery($):
Uncaught TypeError: Cannot read property 'fn' of undefined
以及引发此错误的代码:
$.fn[_iCheck] = function(options, fire) { ... }
我已经检查过,并且在代码中此处未定义$。 我想我已经在webpack中正确设置了jQuery。 我有npm安装它,我要求它像这样:
var jQuery = require('jquery');
然而我仍然得到错误抱怨$未定义。
这是我的webpack.config.js。 我已经删除了我在阅读stackoverflow上的一些其他帖子后所做的修改:
var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
debug: true,
devServer: {
historyApiFallback: true,
contentBase: 'src/public',
publicPath: '/__build__'
},
entry: {
'app': './src/app/bootstrap',
'vendor': './src/app/vendor.ts'
},
output: {
path: root('__build__'),
filename: '[name].js',
sourceMapFilename: '[name].js.map',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: ['', '.ts', '.js', '.json', '.css', '.html']
// ,
// alias: { jquery: 'jquery/src/jquery'}
},
module: {
loaders: [
{ test: /\.json$/, loader: 'json' },
{ test: /\.css$/, loader: 'raw' },
{ test: /\.html$/, loader: 'html' },
{
test: /\.ts$/,
loader: 'ts',
exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
},
{
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
},
{
test: /\.(woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&minetype=application/font-woff"
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader"
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),
new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" })
]
};
function root(args) {
args = sliceArgs(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = sliceArgs(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
有人可以帮忙吗?
由于webpack使用模块,但jQuery需要是全局的,因此需要一种解决方法。
您需要使用公开加载器
require("expose?$!jquery");
要么
module: {
loaders: [
{ test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
]
}
有关更详细的说明,请参阅: https : //65535th.com/jquery-plugins-and-webpack/
用以下内容替换您的require语句:
window.$ = window.jQuery = require('jquery');
这会正确设置窗口对象上的$
(和jQuery
)属性(类似于使用基本JS中的脚本标记)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.