如何在简单的打字稿中导入节点模块

How to import node modules in simple typescript

我是 TypeScript 的新手,我只是想包含一个从节点模块导入的模块。我没有使用 webpack 或任何其他构建工具,因为我试图让这个尽可能简单易懂。

这是我的结构:

/node_modules    -- contains node modules I want to import in main.ts
/scripts/ts/main.ts
/scripts/main.js -- the transpiled main.ts file
/index.html      -- includes the module script tag for scripts/main.js
/package.json
/tsconfig.json

这是我的 tsconfig.json:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "ES2015",
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "outDir": "scripts",
        "moduleResolution": "Node",
        "experimentalDecorators": true
    },
    "$schema": "https://json.schemastore.org/tsconfig",
    "exclude": [],
    "include": [
        "scripts/ts/**/*"
    ]
}

我的 main.ts 文件有这些导入:

import { css, html, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';

main.ts 文件被转译并且 main.js 被成功加载。但是我得到这个错误:

Uncaught TypeError: Failed to resolve module specifier "lit". Relative references must start with either "/", "./", or "../".

导入语句“按原样”转译。它们在转译文件中看起来完全一样,所以我想问题是模块路径错误:浏览器不知道“lit”在“node_modules/lit”中,当我手动更改转译文件中的路径时文件到 ../node_modules/lit/index.js 然后我得到另一个错误是

Uncaught TypeError: Failed to resolve module specifier "@lit/reactive-element". Relative references must start with either "/", "./", or "../".

我想这是一个由其他 lit 模块导入层次结构的模块。 基本上我的导入路径没有正确转译,我不知道该怎么做。 任何帮助都会很棒!

感谢@cdimitroulas 让我思考这个问题。

ES6 导入需要有一个绝对或相对路径——“纯节点导入”根本不起作用,这些路径需要以某种方式解析,不仅对于主模块的导入,而且对于每个其他模块的导入依赖项图。

Typescript 编译器不处理这个问题,因此当前设置缺少一个工具来解析这些路径(如 web-dev-server)或将模块及其所有依赖项捆绑在一个文件中(如 webpack)从而无需解析路径。