如何使用NodeJS 13和Typescript 3.8导入esm模块?

编程入门 行业动态 更新时间:2024-10-09 06:23:26

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用NodeJS 13和Typescript 3.8导入esm模块?"/>

如何使用NodeJS 13和Typescript 3.8导入esm模块?

我对NodeJS中的某些导入有问题。我想使用Typescript 3.8的新功能,例如私有字段:#myPrivateField

我不知道如何在我的班级中正确导入模块“ typescript”。我尝试了许多选择,但无法解决我的问题。

我的文件:

package.json

{
  "name": "test",
  "scripts": {
    "start": "tsc && node --experimental-modules --es-module-specifier-resolution=node main.js"
  },
  "dependencies": {
    "@types/node": "^13.13.2",
    "app-root-path": "^3.0.0",
    "fs-extra": "^9.0.0",
    "tsutils": "^3.17.1"
  },
  "devDependencies": {
    "ts-node": "~8.3.0",
    "typescript": "^3.8.3"
  },
  "type": "module"
}

tsconfig.json

{
  "compilerOptions": {
    "lib": [
      "ESNext",
      "es2016",
      "dom",
      "es5"
    ],
    "module": "esnext",
    "moduleResolution": "Node",
    "sourceMap": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types"
    ]
  }
}

main.ts

// import ts = require("typescript");
import * as ts from "typescript";

export class Main {

    node: ts.Node;
    #test = 'zzz';

    constructor() {}

    process(): void {
        ts.forEachChild(this.node, function cb() {
        });
        console.log('#test', this.#test);
    }
}

const main = new Main();
main.process();

使用此代码,当我运行npm run start时出现错误TypeError: ts.forEachChild is not a function

没有与ts.forEachClid()的一行,它正确记录了私有字段#test的值。

如果尝试用import * as ts from "typescript";替换import ts = require("typescript");,则出现错误TS1202: Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead

当然,我在tsconfig.json和package.json中尝试了许多更改(使用“” type“ =” module“,但无法解决此问题。

我什至尝试将"module": "esnext"替换为"module": "commonjs",但出现错误exports is not defined

备注:这不是特定于模块“打字稿”的。我对其他模块(例如“ fs-extra”)也存在相同的问题,这些模块与大多数传统的NodeJS模块以不同的方式进行导出。

例如,模块“打字稿”以export = ts导出。

我也找到了这个参考,但是并没有太大帮助:.html

我的nodeJs版本是13.3.0,我的打字稿版本是3.8.3感谢您的帮助

回答如下:

ESM模块仍处于实验模式,有许多模块不支持它,例如使用module.exports(CommonJS)代替export(ESM)。

您最好的选择是使用commonjs模块并运行node而没有任何标志。另外,type中程序包的package.json也必须为commonjs


回答您的问题“如何导入ESM模块” ......,以防万一,模块是否支持 ESM模块,您可以像往常一样使用import

import { something } from './something';

更多推荐

如何使用NodeJS 13和Typescript 3.8导入esm模块?

本文发布于:2024-05-07 20:23:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   模块   NodeJS   Typescript   esm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!