pnpm结合vite-plugin-dts插件打包报错
问题描述
- 包管理工具使用 pnpm
- 使用 vite-plugin-dts 插件,对 vue 文件生成 d.ts 类型描述文件
- 自己编写的 ts 或 vue 文件中,引入了第三方依赖
报错信息
报错信息如下
error TS2742: The inferred type of '_sfc_main' cannot be named without a reference to '.pnpm/registry.npmmirror.com+vue-router@4.1.6_vue@3.2.45/node_modules/vue-router'. This is likely not portable. A type annotation is necessary.
error TS2742: The inferred type of '_sfc_main' cannot be named without a reference to '.pnpm/registry.npmmirror.com+element-plus@2.2.1_vue@3.2.45/node_modules/element-plus'. This is likely not portable. A type annotation is necessary.
报错原因
上面的报错信息是指找不到第三方依赖的类型声明
解决方案
报错信息中,提示哪个依赖的类型声明文件找不到,就将这个加入tsconfig.json
以上面的报错信息为例,上面报错信息,提示找不到 vue-router, element-plus 的类型声明文件。那就显示的在 tsconfig.json的paths配置 中将这两个加上
json
{
"compilerOptions": {
// 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
"target": "ESNext",
"useDefineForClassFields": true,
// 指定生成代码模块的标准: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
// 指定 jsx 代码的生成: 'preserve', 'react-native', or 'react'
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
/* 注意:如果未指定--lib,则会注入默认的librares列表。注入的默认库为:
对于 --target ES5: DOM,ES5,ScriptHost
对于 --target ES6: DOM,ES6,DOM.Iterable,ScriptHost
TS 绝不会在您的代码中注入polyfill,所以需要你自己制定编译lib */
"lib": ["ESNext", "DOM"],
// allowJs: 是否允许编写和使用js(包括js,jsx). 默认:false, 可以设置为true, 减少引入非ts模块时提示没有类型声明的问题
// "allowJs": true,
// 是否生成类型声明文件。如果设为true,编译每个ts文件之后会生成一个js文件和一个声明文件
"declaration": true,
// 是否删除注释
"removeComments": false,
// 生成的类型声明文件的输出路径. ./types表示生成在项目根目录下的 types 文件夹
"declarationDir": "./types",
"skipLibCheck": true,
// 不生成编译文件
"noEmit": true,
"importHelpers": true, // 不让同样的辅助函数重复的出现在多个文件中
"allowSyntheticDefaultImports": true, // 允许对不包含默认导出的模块使用默认导入。
// types用来指定需要包含的模块,只有在这里列出的模块的声明文件才会被加载进来
"types": ["vite/client", "jest", "pinia-plugin-persist"],
"baseUrl": ".", // 非相对模块的导入可以相对于baseUrl或通过下文会讲到的路径映射来进行解析
"paths": {
// 定义路径别名. 这里的定义是让ts识别路径别名, vite.config.ts中的是让vite识别路径别名
"@/*": ["src/*"],
"lib/*": ["lib/*"],
"element-plus": ["node_modules/element-plus"],
"vue-router": ["node_modules/vue-router"]
// 如果加入上面两行还不行,那就把上面两行注释掉,把下面这一行的注释打开
// "*": ["node_modules/*"]
}
},
// 定义扫描路径. 会扫描这些路径下的代码
"include": ["src/**/*", "lib/**/*"],
"references": [{ "path": "./tsconfig.node.json" }]
}
参考资料
vite-plugin-dts issues: This is likely not portable. A type annotation is necessary