找不到 webpack 模块:错误:无法解析“jquery”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43198547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:19:47  来源:igfitidea点击:

webpack Module not found: Error: Can't resolve 'jquery'

jquerywebpackhandlebars.js

提问by sdMarth

When I run the 'webpack' command, I get this error:

当我运行 'webpack' 命令时,出现此错误:

ERROR in ./js/main.js Module not found: Error: Can't resolve 'jquery' in '...\js' @ ./js/main.js 3:0-16 4:0-23

未找到 ./js/main.js 模块中的错误:错误:无法解析 '...\js' @ ./js/main.js 3:0-16 4:0-23 中的 'jquery'

In package.json I have:

在 package.json 我有:

"devDependencies": {
   "handlebars": "^4.0.6",
   "handlebars-loader": "^1.4.0",
   "jquery": "^3.2.1",
   "path": "^0.12.7"
},

in webpack.config.js:

在 webpack.config.js 中:

var path = require("path");

module.exports = {
  entry: "./js/main.js",
  output: {
    path: __dirname + "/js",
    filename: "scripts-bundled.js"
  },
  resolve: {
    modules: [
      path.join(__dirname, "js/helpers")
    ]
  },
  module: {
    loaders: [
      {test: /\.hbs$/, loader: "handlebars-loader"}
    ]
  }
};

and in main.js at the top of the file, I have:

在文件顶部的 main.js 中,我有:

import $ from 'jquery';

I'm also using handlebars in main.js. Could it be that handlebars or handlebars-loader is interfering with the jquery? I've used webpack and jquery without this issue before in another project where I didn't use handlebars, but maybe it has nothing to do with it.

我也在 main.js 中使用了把手。可能是handlebars 或handlebars-loader 干扰了jquery?我之前在另一个没有使用把手的项目中使用过 webpack 和 jquery 没有这个问题,但也许它与它无关。

回答by Michael Jungo

The handlebars has nothing to do with it. The problem is that you changed resolve.modulesto [path.join(__dirname, "js/helpers")]. So webpack will only look in js/helpersfor any module, but jqueryand other dependencies from npm are in node_modules. The default value of resolve.modulesis ["node_modules"]. You also need to add node_modulesto keep the regular module resolution.

车把与它无关。问题是,你变resolve.modules[path.join(__dirname, "js/helpers")]。因此 webpack 只会查找js/helpers任何模块,但jquery来自 npm 的其他依赖项在node_modules. 默认值resolve.modules["node_modules"]。您还需要添加node_modules以保持常规模块分辨率。

resolve: {
  modules: [
    path.join(__dirname, "js/helpers"),
    "node_modules"
  ]
},

回答by Ebrahim

Well in my case it was something about importing jqueryinstead of jQuery, it is a webpack config:

好吧,就我而言,它是关于导入jquery而不是jQuery 的,它是一个 webpack 配置:

externals: {
    // require("jquery") is external and available
    //  on the global var jQuery
    "jquery": "jQuery"
}

have a look at this: webpack Can't resolve 'jquery'

看看这个: webpack Can't resolve 'jquery'