You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需打包工具,在TypeScript中使用外部rot-js的配置难题

解决方案:无打包工具在TypeScript中使用rot-js

针对不使用打包工具、在浏览器环境配合TS使用rot-js的场景,以下两种方案可解决类型识别、编译输出的冲突问题:

方案一:全局变量模式(无需模块导入)

这种模式下,rot-js通过<script>标签全局引入,TS代码直接使用全局ROT变量,同时获得完整类型校验。

步骤1:安装rot-js

npm install rot-js --save-dev

仅用于获取内置的类型定义,无需打包到最终代码。

步骤2:配置tsconfig.json

关键是让TS以脚本模式编译,不生成模块导入语句:

{
  "compilerOptions": {
    "target": "ES2020", // 适配现代浏览器
    "module": "None", // 禁用模块处理,生成普通脚本
    "strict": true, // 开启严格类型校验
    "typeRoots": ["./node_modules/@types", "./node_modules/rot-js/lib"] // 指向rot-js的类型文件目录
  },
  "include": ["src/**/*", "globals.d.ts"]
}

步骤3:声明全局ROT类型

在项目根目录创建globals.d.ts文件,关联rot-js的类型:

/// <reference types="rot-js" />
declare global {
  // 让TS识别全局ROT变量,并赋予rot-js的完整类型
  const ROT: typeof import("rot-js");
}
export {};

步骤4:编写TS代码

直接使用全局ROT变量,TS会自动做类型校验:

// src/main.ts
const display = new ROT.Display({ width: 80, height: 25 });
document.body.appendChild(display.getContainer());
display.draw(0, 0, "Hello ROT.js!", "#fff", "#000");

步骤5:浏览器运行

编译TS代码后,在HTML中按顺序引入rot-js和编译后的JS:

<!-- 引入rot-js的全局脚本 -->
<script src="./node_modules/rot-js/dist/rot.js"></script>
<!-- 引入编译后的TS代码 -->
<script src="./dist/main.js"></script>

方案二:ES模块+Import Maps模式(保留模块语法)

如果偏好使用ES模块语法,可通过浏览器的Import Maps功能映射模块路径,同时让TS正确识别类型。

步骤1:安装rot-js

同方案一:

npm install rot-js --save-dev

步骤2:配置tsconfig.json

让TS编译为ES模块,并正确解析rot-js的路径和类型:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext", // 生成ES模块代码
    "moduleResolution": "Bundler", // 适配浏览器模块解析逻辑
    "strict": true,
    "paths": {
      // 让TS将"rot-js"导入指向本地dist文件
      "rot-js": ["./node_modules/rot-js/dist/rot.js"]
    },
    "typeRoots": ["./node_modules/@types", "./node_modules/rot-js/lib"]
  },
  "include": ["src/**/*"]
}

步骤3:编写TS代码

使用标准ES模块导入语法,TS会自动校验类型:

// src/main.ts
import * as ROT from "rot-js";

const display = new ROT.Display({ width: 80, height: 25 });
document.body.appendChild(display.getContainer());
display.draw(0, 0, "Hello ROT.js!", "#fff", "#000");

步骤4:浏览器运行

编译TS代码后,在HTML中添加Import Maps并引入模块脚本:

<!-- 配置Import Maps,映射rot-js的模块路径 -->
<script type="importmap">
{
  "imports": {
    "rot-js": "./node_modules/rot-js/dist/rot.js"
  }
}
</script>
<!-- 以模块方式引入编译后的TS代码 -->
<script type="module" src="./dist/main.js"></script>

关键说明

  • 两种方案均无需编写自定义类型声明,直接复用rot-js自带的.d.ts文件
  • 方案一适合传统脚本场景,无模块语法;方案二符合现代ES模块规范,需浏览器支持Import Maps(现代浏览器均已支持)
  • 若VSCode智能感知仍有异常,可尝试重启TS服务(Ctrl+Shift+P → 选择"TypeScript: Restart TS Server")

内容的提问来源于stack exchange,提问作者jakob gaardsted

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:45:37