【问题标题】:How to import node modules in simple typescript如何在简单的打字稿中导入节点模块
【发布时间】:2021-08-20 21:26:26
【问题描述】:

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

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

【问题讨论】:

  • 您的html 文件是什么样的?它只是从scripts/main.js 导入吗?如果是这样,我认为问题在于 Typescript 不处理将您的依赖项捆绑到一个文件中,这就是为什么这不起作用。这通常是 webpack 的用武之地。关于避免使用 webpack 的类似问题已经被问到:stackoverflow.com/q/47818983/7133623
  • 是的,它只是做一个<script type="module" src="scripts/main.js">。嗯...我认为它不需要将它捆绑在一个文件中。模块可以引用他们只需要知道在哪里看的其他模块吗?我去看看链接,谢谢!
  • 你是对的 - 问题是浏览器不知道解析导入到 node_modules 文件夹。可能你可以像这个答案一样手动编写 node_modules 路径:stackoverflow.com/a/52558858/7133623
  • 当我这样做时,我得到了Uncaught TypeError: Failed to resolve module specifier "@lit/reactive-element". Relative references must start with either "/", "./", or "../". 我不直接使用@lit/reactive-element 所以这一定是依赖关系图中较低的导入。无论如何你是对的,我现在记得 ES6 导入需要有一个绝对或相对路径 - “普通节点导入”根本不起作用,这些需要以某种方式翻译,不仅适用于我的模块,而且适用于所有其他模块下依赖图。非常感谢您抽出宝贵时间讨论这个问题。
  • 最后我使用了 webpack。仅使用 TypeScript 编译器是不够的,我现在正在学习对整个构建过程的不同组件的需求。 webpack 包看起来不仅包括我的模块(尽管这是我唯一提供的东西),而且包括所有的导入,我猜测这些导入的所有依赖项也是如此。我只花了 10 个小时就明白了这一切。

标签: javascript node.js typescript npm es6-modules


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2017-02-21
    • 2021-12-25
    • 1970-01-01
    • 2016-06-14
    • 2015-03-07
    • 2018-06-10
    • 2016-04-12
    • 1970-01-01
    相关资源
    最近更新 更多