4.五步教你生成组件类型文件global.d.ts

345 阅读1分钟

项目使用ts进行编写,可以使用vite-plugin-dts打包出对应的ts类型

话不多说,直接开撸

在之前的项目进行修改

// 拉取项目案例
git clone https://gitee.com/LAMMUpro/article-web-component.git
// 进入项目目录
cd ./article-web-component/web-component-ui
// 回退代码到指定点
git reset --hard 62c4ada2370b6fd097b83f8bc756741a6e932f7b
  1. 安装依赖

    yarn add vite-plugin-dts@3.9.1 -D
    
  2. vite.config.ts

    import dts from 'vite-plugin-dts';
    
    export default defineConfig({
      plugins: [
        dts({
          // 指定使用的 tsconfig.json 文件
          tsconfigPath: './tsconfig.json',
          // 是否将 .vue 文件生成 .d.ts 文件
          insertTypesEntry: true,
          // 指定类型声明文件的输出目录
          outDir: 'dist/types',
          // 是否生成类型声明文件的源码映射
          copyDtsFiles: true,
          // 是否生成静态导入的类型声明文件
          staticImport: true,
        }),
      ]  
    })
    
  3. tsconfig.json

    moduleResolution设置成bundler才能在本项目据有组件提示

    {
    	"compilerOptions": {
    		"target": "ESNext",
    		"module": "Node16",
    		"moduleResolution": "bundler",
    		"allowJs": true,
    		"checkJs": true,
        "allowImportingTsExtensions": true,
        "noEmit": true,
    
    		/* react Config */
    		"jsx": "react-jsx",
    		"jsxImportSource": "react",
    		"skipLibCheck": true,
        "baseUrl": "./",
    		"paths": {
          "@/*": ["./src/*"],
    		},
    		"types": ["vite/client", "@vue/runtime-core"]
    	},
    	"include": ["node_modules/vite/client.d.ts", "scripts", "src/**/*.vue", "src/**/*.ts", "src/**/*.d.ts"],
      "ts-node": {
        "esm": true
      }
    }
    
  4. package.json

    打包不要进行ts类型校验

    {
      "scripts": {
        "build": "vite build",
      },
      "exports": {
        "./global.d.ts": {
          "types": "./dist/types/src/global.d.ts"
        },
        ".": {
          "types": "./dist/types/index.d.ts",
          "default": "./dist/js/index.js"
        },
        "./*": {
          "types": "./dist/types/components/*.d.ts",
          "default": "./dist/js/components/*.js"
        }
      },
    }
    
  5. global.d.ts

    web-component-ui\src\global.d.ts

    import { Button } from './components/button';
    import { Tag } from './components/tag';
    
    // GlobalComponents for Volar
    declare module '@vue/runtime-core' {
      export interface GlobalComponents {
        FlButton: typeof Button
        FlTag: typeof Tag
      }
    
      interface ComponentCustomProperties {
    
      }
    }
    
    export {}
    
  6. 打包

    yarn build
    

    将这个打包产物发npm包,另一个vue3项目的tsconfig.json引入dist\types\src\global.d.ts文件,即可获得组件对应的ts类型提示

    {
        "types": ["web-component-ui/global.d.ts"],
    }