代码之家  ›  专栏  ›  技术社区  ›  Stav Alfi

如何使用Webpack生成d.ts和d.ts.map文件?

  •  4
  • Stav Alfi  · 技术社区  · 7 年前

    我找不到使用Webpack生成d.ts和d.ts.map文件的方法。babel加载程序只生成js和js.map文件。我还需要d.ts和d.ts.map文件(我可以使用 tsc 命令)如图所示:

    enter image description here

    以下是包含所有设置的最小回购: https://github.com/stavalfi/lerna-yarn-workspaces-example

    更多详细信息

    我搬到了Lerna+纱线公司。我的一个包裹是 core (将在其他包中使用)用TS和JS编写。

    我使用的是Webpack4,BabelLoader8,用于TS到JS。

    其他包正在尝试查找类型定义和 核心 但我只能生成 index.js index.js.map 使用Webpack:

    output: {
        path: distPath,
        filename: 'index.js',
      },
    {
      "extends": "../tsconfig.settings.json",
      "compilerOptions": {
        "declaration": true,
        "declarationMap": true,
        "declarationDir": "dist",
        "rootDir": "src",
        "outDir": "dist"
      }
    }
    
    • 当我编译时 TSC (没有webpack),一切都很好,正如我在上面的图片中所示。

    我的策略是错误的吗?我该怎么办?


    我尝试过很多生成d.ts文件的插件,但它们不工作,也不创建 d.ts.map 文件夹。

    我已经试过了: typescript-declaration-webpack-plugin , npm-dts-webpack-plugin , dts-bundle-webpack , @ahrakio/witty-webpack-declaration-files . (它们列在package.json中 核心 所以你可以克隆并使用它)。

    2 回复  |  直到 7 年前
        1
  •  4
  •   edwin    7 年前

    您可以调用类型脚本编译器 tsc 直接这样做。

    使用 tsc --declaration 输出A .d.ts 文件和 tsc --declarationMap 生成相应的映射文件。

    您可以在此处找到更多文档: https://www.typescriptlang.org/docs/handbook/compiler-options.html

        2
  •  0
  •   Shanon Jackson    7 年前

    问题是,我怀疑您有“allowjs”:在您要扩展的tsconfig中为true,当allowjs和declaration true同时打开时,不会生成声明。

    您也不需要特定于类型的加载程序,只需在tsconfig中声明为true,并使用标准的typescript加载程序将类型构建到tsconfig中指定的输出目录,而不是Webpack中。

        3
  •  0
  •   Stav Alfi    7 年前

    正在运行 ts-loader 之前 babel-loader 会成功的。

    您只需要在配置中指定您想要的声明文件。


    如果使用的是绝对路径,则输出的d.ts文件也将包含无效的绝对路径,并将导致类型脚本编译错误。

    为了解决这个问题,我编写了一个插件来将绝对路径转换为相对路径: https://github.com/stavalfi/babel-plugin-module-resolver-loader