【发布时间】:2021-03-05 18:04:42
【问题描述】:
我正在使用 ESModules 编写 Node.js 代码(在 TypeScript 中),我需要访问 __dirname。为了在 CommonJS 中访问等效于 __dirname 的 ESM,我调用了 dirname(fileURLToPath(import.meta.url))。我还在 Jest 中使用 TypeScript 编写测试。使用this 指南,我设置了 Babel。当我运行jest 命令时,我得到了
const DIRNAME = (0, _path.dirname)((0, _url.fileURLToPath)(import.meta.url));
^^^^
SyntaxError: Cannot use 'import.meta' outside a module
这是我写的文件
someCode.ts:
import { dirname } from "path";
import { fileURLToPath } from "url";
const DIRNAME = dirname(fileURLToPath(import.meta.url));
export const x = 5;
someCode.test.ts:
import { x } from "./someCode";
it("Returns 5 as the result", () => {
expect(x).toEqual(5);
});
.babelrc.json:
{
"presets": [
["@babel/preset-env", { "targets": { "node": "current" } }],
"@babel/preset-typescript"
]
}
tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node"
},
"include": ["./src/**/*.ts", "./src/**/*.js"]
}
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.12.7",
"@babel/preset-env": "^7.12.7",
"@babel/preset-typescript": "^7.12.7",
"jest": "^26.6.3",
"typescript": "^4.1.2"
}
}
环境:
- 节点:14.1.0
- 查看
package.json了解模块版本
【问题讨论】:
-
您正在遵循使用 CommonJS 模块的通用指南。对于原生 ESM,请参阅 jestjs.io/docs/en/ecmascript-modules
-
我正在寻找相同问题的答案。将 Jest 移至 ESM 模块似乎太过分了。
标签: typescript jestjs babeljs