安装jQuery会导致webpack错误

时间:2017-07-07 18:55:07

标签: jquery webpack webpack-2 jsdom

我npm安装了jQuery,现在看到一堆Module not found: Error: Can't resolve...错误。知道根本问题可能是什么和解决方案吗?

ERROR in ./node_modules/jquery/lib/node-jquery.js
Module not found: Error: Can't resolve 'jsdom'...

ERROR in ./node_modules/jquery/lib/node-jquery.js
Module not found: Error: Can't resolve 'xmlhttprequest'...

ERROR in ./node_modules/jquery/lib/node-jquery.js
Module not found: Error: Can't resolve 'location'...

ERROR in ./node_modules/jquery/lib/node-jquery.js
Module not found: Error: Can't resolve 'navigator'...

我很确定在搜索错误之后这与webpack 2有关,但是所提出的解决方案都没有解决错误。

我见过但不起作用的一个解决方案是将以下内容放入我的webpack配置中:

plugins: [
  new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
  })
],

这是我的index.html:

<html>
  <head>
    <meta charset="utf-8">
    <title>Title</title>
  </head>
  <body>
    <div id="fb-root"></div>
    <div id="app"></div>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
    <script src="common.js"></script>
    <script src="bundle.js" type="text/javascript"></script>
  </body>
</html>

这是我的webpack.config.js:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'public');
var APP_DIR = path.resolve(__dirname, 'src', 'js');

var node_dir = __dirname + '/node_modules';

var config = {
	entry: {
	  app: APP_DIR + '/index.js',
	  common: ["jquery"],
	},
	output: {
		path: BUILD_DIR,
		filename: 'bundle.js'
	},
	resolve: {
		// This is so that you don't have to write the file extension while importing it.
		// Instead of import HomeComponent from './HomeComponent.jsx'
		// you can do import HomeComponent from './HomeComponent'
		extensions: ['.js', '.jsx','.json', '*'],
		alias: {
      'jquery': node_dir + '/jQuery/src/wrapper.js',
    },
	},
	externals: {
    jquery: 'jQuery'
  },
	plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "common",
      filename: "common.js",
      minChunks: Infinity,
    }),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      jquery: "jquery",
      "window.jQuery": "jquery",
    }),
  ],
	module: {
    loaders : [
			{
				test : /\.jsx?/,
				include : APP_DIR,
				exclude: /node_modules/,
				loader : 'babel-loader'
			}
		],
	},
};

module.exports = config;

这是错误:enter image description here

1 个答案:

答案 0 :(得分:17)

您是否安装了jQuery npm包而不是jquery包?使用已弃用的'jQuery'我有同样的错误。当我删除'jQuery'并安装'jquery'时,错误就消失了。