【发布时间】:2020-12-23 19:43:57
【问题描述】:
我一直在尝试在 nodejs 中导入一个用 typescript 编写的 ESM 模块。但我收到以下错误:
An import path cannot end with a '.ts' extension.
Util.ts
export class Util {
constructor ( ) {
}
log(msg) {
console.log(msg)
}
}
index.ts
import {log} from './Util.ts'
log(task.query.criteria, payload.parameters)
我还在package.json 中添加了"type":"module"
我将 .ts 更改为 .js 只是为了看看它是否有效,然后我得到了:
Object.defineProperty(exports, "__esModule", { value: true }); ^
ReferenceError: exports is not defined
at file:///C:/Users/abc/NestJsPOC/NestPOC/dist/main.js:2:23
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
}
}
编辑
我也试过了:
var log = require('../utility/util.js');
Util.js
function log(msg) {
console.log(msg)
}
module.exports= { log}
index.ts
log('hello')
错误:
TypeError: log is not a function
【问题讨论】:
-
@CarloCorradini 抱歉,复制粘贴时出错了。我已经尝试了所有方法。 ".js"、".ts" 并删除所有扩展名。我认为在导入 ESM mdoules 时必须进行扩展。
-
已经是这样了。我在帖子中添加了 tsconfig。
标签: javascript node.js typescript ecmascript-6 nestjs