Ionic 6/Vue.js 3多应用项目中如何导入自定义库?
解决Ionic 6/Vue 3多项目中Common库类型定义缺失问题
问题核心
你通过rollup打包common自定义库后,在主项目导入时触发TS7006: Parameter 'app' implicitly has an 'any' type错误,本质是rollup默认不会输出TypeScript类型定义文件(.d.ts),导致主项目strict模式下无法识别库的类型信息。
分步解决方案
1. 配置TypeScript生成类型定义
在common库的tsconfig.json中,开启类型声明输出:
{ "compilerOptions": { "declaration": true, "declarationDir": "./dist/types", "emitDeclarationOnly": false } }
2. 让rollup打包时包含类型文件
使用@rollup/plugin-typescript插件集成类型生成:
- 先安装依赖:
npm install @rollup/plugin-typescript typescript --save-dev
- 修改
rollup.config.js配置:
import typescript from '@rollup/plugin-typescript'; export default { input: 'src/index.ts', output: [{ file: 'dist/common.js', format: 'es' }], plugins: [ typescript({ tsconfig: './tsconfig.json', declaration: true, declarationDir: 'dist/types' }) ] };
3. 在package.json中指定类型入口
在common库的package.json里添加types字段,让主项目能找到类型文件:
{ "name": "common", "main": "dist/common.js", "types": "dist/types/index.d.ts" }
4. 重新打包并链接
- 执行
rollup -c重新打包common库 - 重新运行
npm link,在app1/app2中重新导入使用
验证效果
保持主项目strict模式开启,导入common库后,TypeScript将自动识别类型,不会再出现隐式any的报错。
内容的提问来源于stack exchange,提问作者Esteban
相关产品推荐
相关产品推荐

