javascript - 如何在简单的打字稿中导入节点模块
问题描述
我是 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 "../".
我想这是一个由其他点亮模块沿层次结构导入的模块。基本上我的导入路径没有正确转换,我不知道该怎么做。任何帮助都会很棒!
解决方案
感谢@cdimitroulas 让我思考这个问题。
ES6 导入需要有一个绝对或相对路径——“普通节点导入”根本不起作用,这些路径需要以某种方式解析,不仅针对主模块的导入,而且针对依赖关系图中的每个其他模块的导入。
Typescript 编译器不处理这个问题,因此当前设置缺少一个工具来解析这些路径(如 web-dev-server)或将模块及其所有依赖项捆绑在一个文件中(如 webpack),从而消除了解析的需要路径。
推荐阅读
- highcharts - Highchart 动态绘制 Legend 标记并触发 mouseover 事件
- python - 在 python 中使用 ZMQ 记录器
- docker - 击中 Docker 容器时由对等方重置连接
- wikidata - 如何在 wikidata 上安装小工具?
- javascript - 根据索引对数组进行分组,组成三个数组
- android - 尝试访问电话号码现在会产生权限错误
- r - 更改字符串向量中的数字
- c# - 如何创建可在项目标准传输时共享的共享参数
- google-apps-script - 使用 GAS 的 Xero API 签名无效
- javascript - 如何将数据从 Java 传递到 JavaScript Web 应用程序?