【问题标题】:Can I make TypeScript include node_modules for transpilation?我可以让 TypeScript 包含 node_modules 以进行编译吗?
【发布时间】:2018-03-13 01:10:49
【问题描述】:

好的,所以我在设置 Node.js TypeScript 项目时遇到了一个有趣的情况。我希望能够使用非相对 require 引用来引用我的本地模块。 TypeScript 和 Node.js 查找模块的方式是在当前目录中查找 node_modules 目录,然后在每个父目录中查找,直到找到包含引用的此类目录。因此,假设我有一个要在以下目录结构中引用的模块:

/node_modules        <-- Main NPM modules dir
    /...
/package.json
/src
    /node_modules    <-- My local modules dir
        /modules
            /myModule.ts
    /scripts
        /init.ts

...在init.ts 中,我像这样引用myModule

import myModule from "modules/myModule";

据我了解,我希望 TypeScript 将我的 node_modules 目录与我所有其他的 .ts 文件目录一起转换到输出 dist 目录,以便 dist 目录看起来像这样:

/node_modules        <-- Main NPM modules dir
    /...
/package.json
/dist
    /node_modules    <-- My local modules dir
        /modules
            /myModule.js
    /scripts
        /init.js

然后,当 Node.js 查找模块时,它会在 dist/node_modules/modules/myModule.js 找到它。所以在这种情况下,我确实希望 TypeScript 在其输入文件中包含 node_modules 目录。不过,我似乎遗漏了一些基本的东西,因为 TypeScript 实际上默认忽略了这个目录。

我的场景是否是包含node_modules 目录的合法场景,如果是这样,当我刚刚运行tsc 时,如何让TypeScript 将其包含在转译中(因此它将使用我的tsconfig.json 文件) ?

更新: 我发现我可以让它包含我的node_modules 目录,方法是将其显式放入.tsconfig.json 中的include 指令中,如下所示:

"include": [
    "./src/node_modules/**/*",
    "./src/**/*"
]

问题仍然存在;我是否在这里遇到了根本性的错误,因为我必须覆盖 TypeScript 默认排除的内容?我已经对此进行了测试,当我将其转换为 node_modules 时,它确实可以正确找到我的本地模块。

【问题讨论】:

  • 我相信 TS 有一种方法可以将非相对模块说明符别名为相对路径。你可以试试这个,而不是整个 node_modules 业务
  • @PitaJ Care 详细说明它是如何做到的?
  • 我也想知道同样的事情。快速浏览一下repo,我认为 dist 文件使用与 dev 文件相同的 node_modules。如果是这样,那看起来就不太对了。无论如何,我没有深入研究它,因为我没有安装 mongodb。一旦我这样做了,我会回来告诉你
  • @paibamboo 关键是该 repo 没有定义 任何 其自己的本地 ES6 模块 - 一切都直接在 .ts 文件中,并且所有包含都是 NPM模块。因此它没有提供任何定义您自己的 ES6 模块的示例,这些模块基本上只是一个带有 export 语句的 .js 文件。
  • 我认为你的问题是当你的 init.ts 导入它时如何正确编译 myModule.ts 而没有明确包含在 tsconfig 中。您从未在问题中提及 ES6 模块。

标签: javascript node.js typescript transpiler


【解决方案1】:

包含node_modules 进行转译是不正确的。因为node_modules 包含javascript,并且在ts 库的情况下不需要第二次编译,所以它们应该在.d.ts 中有声明。

如果你有自定义类型,或者你想将类型添加到一些没有它们的库中,你需要使用自己的 declarations@types/* 包。

在您的tsconfig.json 中,您可以定义类型根(从哪里加载声明)。

{
    "compilerOptions": {
        "typeRoots": ["./declarations", "./node_modules/@types"],
        "types": ["node"],
    }
}

然后您可以安装 npm i --save-dev @types/node@^12 以获取 nodejs v12 的声明。

并在declarations 中为express 定义您自己的声明,例如:./declarations/express/index.d.ts

import * as express from 'express';

declare module 'express' {
    export interface Request {
        user?: {
            id: string;
            name: string;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多