jQuery和webpack:如何要求

我知道关于这个问题有几个类似的问题,但我已经跟随了很多,他们只是部分帮助。

我想要在我的Angular应用程序中使用webpack jQuery。 但是,浏览器抱怨没有findjQuery($):

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/

将您的要求声明replace为以下内容:

 window.$ = window.jQuery = require('jquery'); 

这会正确设置窗口对象上的$ (和jQuery )属性(类似于在基本JS中使用脚本标记)