Jest/Babel 找不到没有路径前缀的模块
Jest/Babel cannot find modules without the path prefix
我正在尝试遵循 Jest getting started guide 但使用 ES6 模块和 Babel.My 根文件夹有两个 javascript 文件 sumfn.js
和 sum.test.js
。我的 sum.test.js
文件如下所示:
import { sum } from 'sumfn';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
然而 Jest 似乎在解析 sumfn
时遇到了问题,尽管它确实找到了文件 sunfn.js
.
● Test suite failed to run
Cannot find module 'sumfn' from 'sum.test.js'
However, Jest was able to find:
'./sumfn.js'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].
如果我将导入行更改为使用 ./sumfn
,它会起作用。然而,从我读到的关于 ES6 导入的内容来看,它似乎应该能够在同一目录中找到文件。这可能在 Jest 中不受支持吗?
您需要添加./
来告诉JavaScript 您要查找的模块可以在以下文件路径中找到,相对于当前文件。所以需要加上./
表示在当前目录下寻找sumfn.js
.
所以我感到困惑的主要原因之一是因为那里有很多过时的 ES6 模块指南。事实上,Google 上的许多顶级结果似乎已经过时。我在看像 this, this, and this 这样的指南,他们都说你可以从模块名称导入,而不指定路径,例如
import { double } from 'mymodule';
这些被称为"bare" import specifiers, and the guides said that it will by default search the current directory for a matching module. However, it seems like right now they are not supported in browsers。
令人非常困惑的是它们 在 BabelJS 和 Webpack 中受支持,但它遵循不同的约定。例如,Webpack 搜索 paths specified in resolve.modules
, which by default includes the node_modules
folder. This is why the Create-React-App example 可以使用像
这样的语句
import React from 'react';
似乎未来的计划是让环境决定如何解析这些 "bare" 说明符 ()。让每个环境以不同的方式解析这些说明符似乎很危险,这可能会使制作交叉兼容的模块变得困难,但我想这就是目前的计划。
我正在尝试遵循 Jest getting started guide 但使用 ES6 模块和 Babel.My 根文件夹有两个 javascript 文件 sumfn.js
和 sum.test.js
。我的 sum.test.js
文件如下所示:
import { sum } from 'sumfn';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
然而 Jest 似乎在解析 sumfn
时遇到了问题,尽管它确实找到了文件 sunfn.js
.
● Test suite failed to run
Cannot find module 'sumfn' from 'sum.test.js'
However, Jest was able to find:
'./sumfn.js'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].
如果我将导入行更改为使用 ./sumfn
,它会起作用。然而,从我读到的关于 ES6 导入的内容来看,它似乎应该能够在同一目录中找到文件。这可能在 Jest 中不受支持吗?
您需要添加./
来告诉JavaScript 您要查找的模块可以在以下文件路径中找到,相对于当前文件。所以需要加上./
表示在当前目录下寻找sumfn.js
.
所以我感到困惑的主要原因之一是因为那里有很多过时的 ES6 模块指南。事实上,Google 上的许多顶级结果似乎已经过时。我在看像 this, this, and this 这样的指南,他们都说你可以从模块名称导入,而不指定路径,例如
import { double } from 'mymodule';
这些被称为"bare" import specifiers, and the guides said that it will by default search the current directory for a matching module. However, it seems like right now they are not supported in browsers。
令人非常困惑的是它们 在 BabelJS 和 Webpack 中受支持,但它遵循不同的约定。例如,Webpack 搜索 paths specified in resolve.modules
, which by default includes the node_modules
folder. This is why the Create-React-App example 可以使用像
import React from 'react';
似乎未来的计划是让环境决定如何解析这些 "bare" 说明符 (