我知道关于这个问题的 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 需要是全局的,因此需要一个解决方法。
您需要使用 expose loader
require("expose?$!jquery");
或
module: {
loaders: [
{ test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" },
]
}
关于javascript - jQuery 和 webpack : how to require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34514211/