如何为 Web Component 包提供 TypeScript 类型定义?

解读

国内前端面试中,面试官问“如何为 Web Component 包提供 TypeScript 类型定义”,并不是想听你背诵 d.ts 语法,而是考察三件事:

  1. 你是否理解 Web Component 在 npm 包中的两种消费形态(源码级 ESM 消费 / 打包后 UMD/ESM 消费);
  2. 你是否能把 Webpack 构建流程与类型系统打通,让类型既能在开发阶段被 tsc/VSCode 识别,又能在打包阶段被正确剥离;
  3. 你是否熟悉国内私有 npm 源(Verdaccio、cnpm、企业 Nexus)的发布规范,确保类型文件随包一起发布且能被正确解析。

一句话:让使用者在 import 'my-button' 时,不写任何额外声明就能拿到完整的类型提示,同时 Webpack 打包不会把 d.ts 文件误当成资源输出。

知识点

  1. Web Component 的“双模块”形态

    • 源码:.ts 文件,使用 declare global { interface HTMLElementTagNameMap {} } 扩展标签名;
    • 产物:经 Webpack + ts-loader/swc-loader 打包后输出 .js + .d.ts 声明文件。
  2. TypeScript 三斜杠指令与 package.json 字段

    • "types"/"typings":入口 d.ts 路径;
    • "exports" 条件导出(Node12+):"types" 条件优先级最高;
    • 三斜杠 /// <reference types="..." /> 仅用于遗留场景,新项目推荐走 package.json。
  3. Webpack 侧的关键配置

    • output.clean 避免旧声明残留;
    • ts-loader 的 transpileOnly: true + fork-ts-checker-webpack-plugin 做并行类型检查,生成 d.ts;
    • declarationDir 与 outDir 分离,防止把类型打包进 bundle;
    • externals 把 lit、rxjs 等 peerDep 排除,避免重复打包;
    • CopyWebpackPlugin 把 custom-elements.json(Analyzer 生成)拷贝到 dist,供 Storybook/Vetur 使用。
  4. 国内 npm 发布注意

    • .npmignore 里把 src、webpack.config.js 排除,但保留 dist/**/*.d.ts;
    • 私有源发布前执行 npx publint 检测入口字段是否正确;
    • 若包名带 @company 作用域,需在 package.json 显式写 "publishConfig":{"registry":"https://npm.xxx.com"},否则默认打到官方源。
  5. 使用端零配置体验

    • 使用者在项目里只要 tsconfig.json 的 moduleResolution 设为 node16/bundler,就能根据 exports.types 自动解析;
    • 若使用 Webpack resolve.extension 默认 ['.tsx', '.ts', '.jsx', '.js'],无需额外别名;
    • 若组件库带主题文件(如 theme/index.css),可在 package.json 里加 "style": "dist/theme/index.css",配合 postcss-import 自动引入。

答案

步骤一:在组件源码里写好类型

// src/my-button.ts
export class MyButton extends HTMLElement {
  static readonly tagName = 'my-button';
  get variant(): 'primary' | 'danger';
  set variant(v: 'primary' | 'danger');
}
declare global {
  interface HTMLElementTagNameMap {
    'my-button': MyButton;
  }
}

步骤二:Webpack 配置把类型文件生成到 dist

// webpack.config.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = {
  mode: 'production',
  entry: './src/index.ts',
  output: { path: path.resolve('dist'), filename: 'index.js', library: { type: 'module' }, clean: true },
  experiments: { outputModule: true },
  resolve: { extensions: ['.ts', '.js'] },
  module: { rules: [{ test: /\.ts$/, use: 'ts-loader' }] },
  plugins: [
    new ForkTsCheckerWebpackPlugin({
      typescript: {
        configOverwrite: {
          compilerOptions: { declaration: true, declarationDir: 'dist', outDir: 'dist', emitDeclarationOnly: false },
        },
      },
    }),
  ],
  externals: { lit: 'lit', 'lit/decorators.js': 'lit/decorators.js' },
};

步骤三:package.json 指向类型入口

{
  "name": "@demo/my-button",
  "version": "1.0.0",
  "type": "module",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    },
    "./theme.css": "./dist/theme/index.css"
  },
  "files": ["dist"],
  "publishConfig": { "registry": "https://npm.xxx.com" }
}

步骤四:本地验证

  1. npm pack 生成 tgz,在空项目 npm i ../demo-my-button-1.0.0.tgz;
  2. 新建 index.ts 写 document.createElement('my-button').variant = 'primary';
  3. 运行 tsc --noEmit 无报错,VSCode 有智能提示即成功。

拓展思考

  1. 微前端场景下,主应用与子应用可能重复注册同名 Custom Element。此时可在 d.ts 里加 export const define: () => void;,由使用端决定是否调用,避免重复定义抛错。
  2. 若组件库体积大,可把每个组件打成单独 chunk,利用 exports["./button"] 子路径导出,配合 tsconfig.paths 实现按需加载;Webpack 5 experiments.outputModule 支持 import('@demo/my-button/button') 动态导入,tree-shaking 更精准。
  3. 国内很多项目仍用 Webpack4,不支持 exports 字段,此时需要再补一份 "main": "dist/index.js" + "types": "dist/index.d.ts" 的降级方案,并在 README 中说明 moduleResolution: node 即可兼容。