经过很长一段时间的间隔后,我正在将一个“旧的打字稿项目”更新为节点等的现代版本。修复了一堆 linter 错误后,我收到了一个奇怪的错误:
TSError: ⨯ Unable to compile TypeScript:
src/frames/frame.ts:28:7 - error TS2451: Cannot redeclare block-scoped variable 'frames_1'.
28 const frames_1 = require("../frames");
~~~~~~~~
src/execute/eval-pipe.ts:4:7
4 const frames_1 = require("../frames");
~~~~~~~~
'frames_1' was also declared here.
这显然是由于打字稿编译器从不同的导入语句创建非局部变量:
= 框架.ts
export {}
import * as _ from 'lodash'
import { MetaFrame, NilContext } from '../frames'
= eval-pipe.ts
export {}
import { Context, Frame, NilContext } from '../frames'
这怎么可能?我向每个文件添加了
export {}
以确保所有内容都在模块范围内。我需要不同的配置吗?
= tsconfig.json{
"compilerOptions": {
"declaration": false,
"esModuleInterop": true,
"lib": ["es6"],
"module": "commonjs",
"target": "ESNext",
"moduleResolution": "node",
"noImplicitAny": false,
"outDir": "./lib",
"preserveConstEnums": true,
"removeComments": true,
"skipLibCheck": true,
},
"include": [
"src/**/*.ts"
],
"exclude": [
"test/**/*-spec.ts"
]
}
==更新
如果按照建议,我删除了
"require": "ts-node/register"
从 mocha_opts 中,我得到了错误:
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/ernest/Developer/hclang/node_modules/chalk/source/index.js from /Users/ernest/Developer/hclang/src/execute/hc-eval.ts not supported.
Instead change the require of index.js in /Users/ernest/Developer/hclang/src/execute/hc-eval.ts to a dynamic import() which is available in all CommonJS modules.
这让我想知道这行
import chalk from 'chalk'
是否格式错误或没有被正确解释。
FWIW,这是我最终解决(那些)问题的配置文件。奇怪的是,有几个测试文件仍然给出奇怪的 .ts 错误,但我现在可以解决这些问题。
package.json(部分)
"type": "module",
"directories": {
"lib": "./lib",
"src": "./src",
"test": "./test"
},
"files": [
"lib"
],
tsconfig.json
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"outDir": "./lib",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
.mocharc.json
{
"extension": ["ts"],
"require": "ts-node/register"
}