百科狗-知识改变命运!
--

模块 nodejs - TypeScript 模块类型

是丫丫呀1年前 (2023-11-21)阅读数 20#技术干货
文章标签带来了

模块 nodejs

在过去的几年里,Node.js一直致力于支持运行 ECMAScript 模块(ESM)。自节点创建以来,这是一个非常难支持的功能。js 生态系统是建立在一个名为 CommonJS(CJS)的不同模块系统上的。

两个模块系统之间的互操作带来了巨大的挑战,有许多新的特性需要处理;然而,Node.js中对 ESM 的支持现在已经在 Node.j 中实现,尘埃落定。

这就是为什么TypeScript带来了两个新的modulemoduleResolution设置:node16nodenext

{
    "compilerOptions": {
        "module": "nodenext",
    }
}

这些新模式带来了一些高级特性,我们将在这里进行探讨。

typeinpackage.jsonand New Extensions

Node.js supports a new setting in package.json called type."type" can be set to either "module" or "commonjs".

{
    "name": "my-package",
    "type": "module",
    "//": "...",
    "dependencies": {
    }
}

This setting controls whether .js files are interpreted as ES modules or CommonJS modules, and defaults to CommonJS when not set. When a file is considered an ES module, a few different rules come into play compared to CommonJS:

  • import/export statements and top-level await can be used
  • relative import paths need full extensions(e.g we have to write import "./foo.js" instead of import "./foo")
  • imports might resolve differently from dependencies in node_modules
  • certain global-like values like require() and __dirname cannot be used directly
  • CommonJS modules get imported under certain special rules

We’ll come back to some of these.

To overlay the way TypeScript works in this system,.ts and .tsx files now work the same way. When TypeScript finds a .ts,.tsx,.js, or .jsx file, it will walk up looking for a package.json to see whether that file is an ES module, and use that to determine:

  • how to find other modules which that file imports
  • and how to transform that file if producing outputs

When a .ts file is compiled as an ES module, ECMAScript import/export syntax is left alone in the .js output; when it’s compiled as a CommonJS module, it will produce the same output you get today under module:commonjs.

This also means paths resolve differently between .ts files that are ES modules and ones that are CJS modules. For example, let’s say you have the following code today:

// ./foo.ts
export function helper() {
    // ...
}
// ./bar.ts
import { helper } from "./foo"; // only works in CJS
helper();

This code works in CommonJS modules, but will fail in ES modules because relative import paths need to use extensions. As a result, it will have to be rewritten to use the extension of the output of foo.ts- so bar.ts will instead have to import from ./foo.js.

// ./bar.ts
import { helper } from "./foo.js"; // works in ESM & CJS
helper();

This might feel a bit cumbersome at first, but TypeScript tooling like auto-imports and path completion will typically just do this for you.

One other thing to mention is the fact that this applies to .d.ts files too. When TypeScript finds a .d.ts file in package, whether it is treated as an ESM or CommonJS file is based on the containing package.

New File Extensions

The type field in package.json is nice because it allows us to continue using the .ts and .js file extensions which can be convenient; however, you will occasionally need to write a file that differs from what type specifies. You might also just prefer to always be explicit.

Node.js supports two extensions to help with this:.mjs and .cjs..mjs files are always ES modules, and .cjs files are always CommonJS modules, and there’s no way to override these.

In turn, TypeScript supports two new source file extensions:.mts and .cts. When TypeScript emits these to JavaScript files, it will emit them to .mjs and .cjs respectively.

Furthermore, TypeScript also supports two new declaration file extensions:.d.mts and .d.cts. When TypeScript generates declaration files for .mts and .cts, their corresponding extensions will be .d.mts and .d.cts.

Using these extensions is entirely optional, but will often be useful even if you choose not to use them as part of your primary workflow.

CommonJS Interop

Node.js allows ES modules to import CommonJS modules as if they were ES modules with a default export.

// @filename: helper.cts
export function helper() {
    console.log("hello world!");
}
 
// @filename: index.mts
import foo from "./helper.cjs";
 
// prints "hello world!"
foo.helper();

In some cases, Node.js also synthesizes named exports from CommonJS modules, which can be more convenient. In these cases, ES modules can use a “namespace-style” import(i.e.import * as foo from "..."), or named imports(i.e.import{helper}from "...").

// @filename: helper.cts
export function helper() {
    console.log("hello world!");
}
 
// @filename: index.mts
import { helper } from "./helper.cjs";
 
// prints "hello world!"
helper();

There isn’t always a way for TypeScript to know whether these named imports will be synthesized, but TypeScript will err on being permissive and use some heuristics when importing from a file that is definitely a CommonJS module.

One TypeScript-specific note about interop is the following syntax:

import foo = require("foo");

In a CommonJS module, this just boils down to a require() call, and in an ES module, this imports createRequire to achieve the same thing. This will make code less portable on runtimes like the browser(which don’t support require()), but will often be useful for interoperability. In turn, you can write the above example using this syntax as follows:

// @filename: helper.cts
export function helper() {
    console.log("hello world!");
}
 
// @filename: index.mts
import foo = require("./foo.cjs");
 
foo.helper()

Finally, it’s worth noting that the only way to import ESM files from a CJS module is using dynamic import() calls. This can present challenges, but is the behavior in Node.js today.

You can read more about ESM/CommonJS interop in Node.js here.

package.jsonExports, Imports, and Self-Referencing

Node.js supports a new field for defining entry points in package.json called "exports". This field is a more powerful alternative to defining "main" in package.json, and can control what parts of your package are exposed to consumers.

模块 nodejs - TypeScript 模块类型

Here’s an package.json that supports separate entry-points for CommonJS and ESM:

// package.json
{
    "name": "my-package",
    "type": "module",
    "exports": {
        ".": {
            // Entry-point for `import "my-package"` in ESM
            "import": "./esm/index.js",
            // Entry-point for `require("my-package") in CJS
            "require": "./commonjs/index.cjs",
        },
    },
    // CJS fall-back for older versions of Node.js
    "main": "./commonjs/index.cjs",
}

There’s a lot to this feature, which you can read more about on the Node.js documentation. Here we’ll try to focus on how TypeScript supports it.

With TypeScript’s original Node support, it would look for a "main" field, and then look for declaration files that corresponded to that entry. For example, if "main" pointed to ./lib/index.js, TypeScript would look for a file called ./lib/index.d.ts. A package author could override this by specifying a separate field called "types"(e.g."types":"./types/index.d.ts").

The new support works similarly with import conditions. By default, TypeScript overlays the same rules with import conditions - if you write an import from an ES module, it will look up the import field, and from a CommonJS module, it will look at the require field. If it finds them, it will look for a colocated declaration file. If you need to point to a different location for your type declarations, you can add a "types" import condition.

// package.json
{
    "name": "my-package",
    "type": "module",
    "exports": {
        ".": {
            // Entry-point for TypeScript resolution - must occur first!
            "types": "./types/index.d.ts",
            // Entry-point for `import "my-package"` in ESM
            "import": "./esm/index.js",
            // Entry-point for `require("my-package") in CJS
            "require": "./commonjs/index.cjs",
        },
    },
    // CJS fall-back for older versions of Node.js
    "main": "./commonjs/index.cjs",
    // Fall-back for older versions of TypeScript
    "types": "./types/index.d.ts"
}

TypeScript also supports the "imports" field of package.json in a similar manner(looking for declaration files alongside corresponding files), and supports packages self-referencing themselves. These features are generally not as involved, but are supported.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)