Deno - 将 TypeScript 导入 JS 文件

Deno - Importing TypeScript into a JS file

在Deno中,要导入TypeScript模块,你自己的代码文件必须是TypeScript吗?还是 Deno 在导入模块之前自动将 TypeScript 转换为 javascript?

我希望我所有的代码文件都是 EcmaScript 模块(js 或 mjs,但不是 ts)。

与现在的其他人不同,我想避免在自己的代码中使用 TypeScript。我不喜欢静态类型的死板,而且 Typescript 不是 EcmaScript 标准的一部分。仅 EcmaScript 就有我管理大型项目所需的一切。对我来说,TypeScript 是一种过时的技术,自 ES6 模块出现以来就不再是必需的了。 TypeScript 解决的问题类型是我没有的问题。

但是,很明显,Deno 中可用的许多第 3 方模块将用 TypeScript 编写。是否可以以在导入之前转换为 JavaScript 的方式导入这些模块,以便我可以保留我自己的纯 EcmaScript 代码?

您可以使用 JavaScript 编写自己的代码。

假设您拥有或正在使用 TypeScript file/module numbers.ts:

export function isEven(n: number): boolean {
    if (n % 2 != 0) {
        return false
    }
    return true;
}

您可以使用 app.js JavaScript 脚本导入并 运行 它:

import { isEven } from "./module.ts";

const one = isEven(1)
const two = isEven(2)

console.log(one)
console.log(two)

Deno 在内部将 TypeScript 转换为 JavaScript。使用标准库或第三方库时,过程是相同的。 Deno 项目的人们更进一步将其添加为目标:

https://deno.land/manual/introduction

Browser compatible: The subset of Deno programs which are written completely in JavaScript and do not use the global Deno namespace (or feature test for it), ought to also be able to be run in a modern web browser without change.

名称解析必须完全限定。在这个使用 TypeScript 的专用页面中有更多关于引用类型定义的内容:

https://deno.land/manual/getting_started/typescript

Deno supports both JavaScript and TypeScript as first class languages at runtime. This means it requires fully qualified module names, including the extension (or a server providing the correct media type)

示例:

import { config } from "https://deno.land/x/dotenv/mod.ts";

按照我上面的示例,您可以使用 bundle 命令生成一个包含所有依赖项的 JavaScript 文件。捆绑它会占用我的 app.jsmodule.ts 文件并创建一个新文件 app.bundle.js 即 JavaScript.

https://deno.land/manual/tools/bundler

$ deno bundle app.js app.bundle.js
Bundling file:///home/pomatti/projects/deno-sandbox/app.js
Emitting bundle to "app.bundle.js"
3111 bytes emmited.
$ deno run app.bundle.js
false
true

甚至可以在浏览器中加载:

Bundles can also be loaded in the web browser. The bundle is a self-contained ES module, and so the attribute of type must be set to "module". For example:

<script type="module" src="website.bundle.js"></script>

至于 ECMAScript 模块,我想指出 TypeScript 也实现了它。

https://github.com/microsoft/TypeScript/issues/2242

https://www.staging-typescript.org/docs/handbook/modules.html

Starting with ECMAScript 2015, JavaScript has a concept of modules. TypeScript shares this concept.

现在,"static type" 讨论超出了本论坛的范围,所以我不会在这里涉及它,但我相信我涵盖了其他所有内容。