简体   繁体   English

"Webpack 无法从包的子目录中解析模块"

[英]Webpack cannot resolve modules from subdirectory of a package

I have a package that is being built to a directory named lib .我有一个包正在构建到名为lib的目录中。 The structure is as follows:结构如下:

- lib/
-- moduleA/
---- index.js
-- moduleB/
---- index.js
- src/
-- moduleA/
-- moduleB/

and in package.json I specify:package.json我指定:

"main": "./lib"

In a different project, I'm trying to import a specific module from the package above, as follows:在另一个项目中,我尝试从上面的包中导入特定模块,如下所示:

import moduleA from '@scope/packageA/moduleA';

but Webpack is not able to resolve the module, saying:但 Webpack 无法解析模块,说:

Module not found: Error: Can't resolve '@scope/packageA/moduleA'找不到模块:错误:无法解析“@scope/packageA/moduleA”

However, it does work if I import directly from lib :但是,如果我直接从lib导入,它确实有效:

import moduleA from '@scope/packageA/lib/moduleA;

Why is this happening?为什么会这样? my understanding is the Webpack respects the main entry of the package, and that it should be possible to import from anywhere in the hierarchy starting from the entry point.我的理解是 Webpack 尊重包的main入口,并且应该可以从入口点开始从层次结构中的任何地方导入。

I might be a few years late, but if someone needs a possible answer for this:我可能晚了几年,但如果有人需要一个可能的答案:

You can use the exports field inside package.json to define which directories resolve to which modules, using the example in the question, you might want to have something like this:您可以使用package.json中的exports字段来定义哪些目录解析到哪些模块,使用问题中的示例,您可能想要这样的东西:

// package.json
{
  ...
  "exports": {
    "./moduleA": "./lib/moduleA/index.js",
    "./moduleB": "./lib/moduleB/index.js",
  },
}

This will help Node to correctly resolve the package import, and "translate" it from:这将帮助 Node 正确解析包导入,并从以下位置“翻译”它:

import moduleA from '@scope/packageA/moduleA';

to:到:

import moduleA from '@scoppe/packageA/lib/moduleA/index.js';

Note that this works for Node v12+, any version before will use the main field as the entry for your package.请注意,这适用于 Node v12+,之前的任何版本都将使用main字段作为包的条目。

There's a lot more to this because you can specify entry points conditionally and use them for builds with different Javascript formats (CommonJS and EMS), be sure to check out the documentation这还有很多,因为您可以有条件地指定入口点并将它们用于具有不同 Javascript 格式(CommonJS 和 EMS)的构建,请务必查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM