我有一个非常简单的项目,用webpack测试运行jQuery函数。但是我在捆绑步骤遇到了错误。以下是错误:
ERROR in ./~/jQuery/lib/node-jquery.js
Module not found: Error: Cannot resolve module 'jsdom' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib
@ ./~/jQuery/lib/node-jquery.js 5:13-29
ERROR in ./~/jQuery/lib/node-jquery.js
Module not found: Error: Cannot resolve module 'xmlhttprequest' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib
@ ./~/jQuery/lib/node-jquery.js 8:28-53
ERROR in ./~/jQuery/lib/node-jquery.js
Module not found: Error: Cannot resolve module 'location' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib
@ ./~/jQuery/lib/node-jquery.js 13:24-43
ERROR in ./~/jQuery/lib/node-jquery.js
Module not found: Error: Cannot resolve module 'navigator' in /home/mypc/IdeaProject/OpenDimSum/frontend/node_modules/jQuery/lib
@ ./~/jQuery/lib/node-jquery.js 17:25-45
以下是我的配置文件:
的package.json
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.16.0",
"babel-preset-react": "^6.16.0",
"jquery": "^2.2.2",
"react": "file:node_modules/react",
"react-dom": "file:node_modules/react-dom",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.16.2"
}
}
webpack.config.js
var webpack = require('webpack')
var path = require('path')
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js',
publicPath: 'public',
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel'
},
{
test: /\.css/,
include: APP_DIR,
}
]
},
};
module.exports = config;
index.jsx:
import React from 'react'
import {render} from 'react-dom'
import $ from 'jQuery'
(function () {
$(document).ready(function() {
console.log("It works!");
});
})();
如果我安装上述模块(jsdom,xmlhttprequest,..),错误将被很长的错误所取代。
答案 0 :(得分:4)
您可以使用webpack.ProvidePlugin
将jQuery解析为全局标识符。当您使用ProvidePlugin
时,您不希望将jQuery
导入模块,因为它可用作全局变量。
类似
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]