如何为 Web Component 包提供 TypeScript 类型定义?
解读
国内前端面试中,面试官问“如何为 Web Component 包提供 TypeScript 类型定义”,并不是想听你背诵 d.ts 语法,而是考察三件事:
- 你是否理解 Web Component 在 npm 包中的两种消费形态(源码级 ESM 消费 / 打包后 UMD/ESM 消费);
- 你是否能把 Webpack 构建流程与类型系统打通,让类型既能在开发阶段被 tsc/VSCode 识别,又能在打包阶段被正确剥离;
- 你是否熟悉国内私有 npm 源(Verdaccio、cnpm、企业 Nexus)的发布规范,确保类型文件随包一起发布且能被正确解析。
一句话:让使用者在 import 'my-button' 时,不写任何额外声明就能拿到完整的类型提示,同时 Webpack 打包不会把 d.ts 文件误当成资源输出。
知识点
-
Web Component 的“双模块”形态
- 源码:
.ts文件,使用declare global { interface HTMLElementTagNameMap {} }扩展标签名; - 产物:经 Webpack + ts-loader/swc-loader 打包后输出
.js+.d.ts声明文件。
- 源码:
-
TypeScript 三斜杠指令与 package.json 字段
"types"/"typings":入口 d.ts 路径;"exports"条件导出(Node12+):"types"条件优先级最高;- 三斜杠
/// <reference types="..." />仅用于遗留场景,新项目推荐走 package.json。
-
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 使用。
-
国内 npm 发布注意
.npmignore里把src、webpack.config.js排除,但保留dist/**/*.d.ts;- 私有源发布前执行
npx publint检测入口字段是否正确; - 若包名带
@company作用域,需在package.json显式写"publishConfig":{"registry":"https://npm.xxx.com"},否则默认打到官方源。
-
使用端零配置体验
- 使用者在项目里只要
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" }
}
步骤四:本地验证
npm pack生成 tgz,在空项目npm i ../demo-my-button-1.0.0.tgz;- 新建
index.ts写document.createElement('my-button').variant = 'primary'; - 运行
tsc --noEmit无报错,VSCode 有智能提示即成功。
拓展思考
- 微前端场景下,主应用与子应用可能重复注册同名 Custom Element。此时可在 d.ts 里加
export const define: () => void;,由使用端决定是否调用,避免重复定义抛错。 - 若组件库体积大,可把每个组件打成单独 chunk,利用
exports["./button"]子路径导出,配合tsconfig.paths实现按需加载;Webpack 5experiments.outputModule支持import('@demo/my-button/button')动态导入,tree-shaking 更精准。 - 国内很多项目仍用 Webpack4,不支持
exports字段,此时需要再补一份"main": "dist/index.js"+"types": "dist/index.d.ts"的降级方案,并在 README 中说明moduleResolution: node即可兼容。