我知道stackoverflow上有几个关于这个问题的类似问题,但我已经跟随了很多解答,它们只有部分地帮助了我。
我正在尝试在我的Angular应用程序中使用webpack来引用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));
}
有人能帮忙吗?
var jQuery = ...
并不能神奇地创建一个名为$
的变量。要么将var jQuery
重命名为var $
,要么更改代码以使用jQuery.fn
而不是$.fn
(无论如何,您都应该这样做,因为$
可以被noConflict
指向完全不同的东西)。 - DCoder