使用 webpack 捆绑资产并生成 Typescript 定义的规范方法

Canonical way to use webpack to bundle assets AND generate Typescript definitions

我有一个项目,它构建了一个包含各种资产的打字稿库。以下是其 webpack 的配置方式:

const path = require("path");

module.exports = {
  entry: "./src/index.ts",
  mode: "development",
  module: {
    rules: [
      {
        test: /\.svg$/i,
        issuer: /\.[jt]sx?$/,
        use: [{ loader: "@svgr/webpack", options: { typescript: true } }],
      },
      {
        test: /\.s[ac]ss$/i,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  output: {
    filename: "my-icons.js",
    path: path.resolve(__dirname, "dist"),
    library: {
      name: "my-icons",
      type: "umd",
    },
  },
};

效果很好。它转换资产,符合 Typescript,并将其全部捆绑。但它不会生成 .d.ts 文件,库的任何 Typescript 使用者都需要这些文件。

我的研究表明:

  1. ts-loaderrecommends using a DeclarationBunderPlugin。不过这是个实验项目,六年没更新了

  2. 其他一些处理此问题的插件似乎没有得到特别好的支持。参见 dts-bundle referenced in this SO question as well as other plugin code provided in answers to that question. There is also a plugin referenced in

  3. 我还看到了仅 运行 tsc 并复制 .d.ts 文件的建议。请参阅 , for example. See also this 中的评论。很好,但我有点惊讶没有看到任何工具来处理这个问题。

  4. 据我所知,webpack 文档在 its typescript section.

    中对此保持沉默

是否有 recommended/best/canonical 方法?它只是上面 3. 的某个版本——即单独生成 .d.ts 文件并手动将它们添加到分发包中吗?

我把 a small example repo 放在一起,演示了单独使用 tscwebpack 的问题。

好吧,我觉得有点傻,但是,另一方面,这似乎不是很好well-documented。

事实证明,如果您的 webpack 和 tsconfig 都设置为 compile/build 到同一目录,并且您的 tsconfig 设置为发出声明,并且您的 webpack 库设置为以相同的入口点为目标package.json 中的主要条目(例如 index.js),它将正常工作。

所以--

package.json:

//excerpt
"main": "lib/index.js",
  "types": "lib/index.d.ts",
  "scripts": {
    "build": "rimraf ./lib && webpack"
  },

tsconfig.json

//excerpt
  "compilerOptions": {
    "outDir": "lib",
    "declaration": true
}

webpack.config.js

const path = require("path");

module.exports = {
  entry: "./src/index.ts",
  mode: "development",
  module: {
    rules: [
      {
        test: /\.svg$/i,
        issuer: /\.[jt]sx?$/,
        use: [{ loader: "@svgr/webpack", options: { typescript: true } }],
      },
      {
        test: /\.s[ac]ss$/i,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, "lib"),
    library: {
      name: "my-icons",
      type: "umd",
    },
  },
};

this repo 中有一个工作示例。只要做 npm install && npm run build