首页 > 解决方案 > 如何在简单的打字稿中导入节点模块

问题描述

我是 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 "../".

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

标签: javascriptnode.jstypescriptnpmes6-modules

解决方案


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

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

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


推荐阅读