Angular 9自定义库引用外部资源文件失败问题求助
解决Angular库中引用第三方依赖资源的问题
为什么angular.json加assets会报错?
Angular库的构建配置(projects.xxx.architect.build)和应用配置不同,库的构建Schema里没有assets这个属性,所以直接添加会触发验证错误,不能这么操作。
可行解决方案
方案1:通过ng-packagr的配置复制第三方资源
Angular库基于ng-packagr构建,在库根目录的ng-package.json里配置assets字段,指定要复制的资源路径:
{ "$schema": "./node_modules/ng-packagr/ng-package.schema.json", "dest": "../../dist/你的库名称", "lib": { "entryFile": "src/public-api.ts" }, "assets": [ { "glob": "**/*", "input": "./node_modules/custom-plugin/assets", "output": "./assets" } ] }
构建完成后,custom-plugin的assets会被复制到库的dist目录下的assets文件夹,这时在库的模板里可以用相对路径引用:
<img src="assets/image.png" alt="示例图片">
方案2:在主应用中配置资源复制(适合库依赖特定主应用的场景)
如果你的库是给固定主应用使用的,可以在主应用的angular.json中配置复制custom-plugin的资源:
"projects": { "你的主应用名称": { "architect": { "build": { "options": { "assets": [ // 保留原有配置 { "glob": "**/*", "input": "node_modules/custom-plugin/assets", "output": "assets/custom-plugin" } ] } } } } }
之后在库的模板里用绝对路径引用:
<img src="/assets/custom-plugin/image.png" alt="示例图片">
方案3:将资源内嵌为base64(适合小型资源)
把图片转为base64内嵌到组件中,彻底避免路径问题。首先在组件TS文件中导入图片:
import imageSrc from 'custom-plugin/assets/image.png'; @Component({ selector: 'lib-你的组件名称', templateUrl: './你的组件.component.html' }) export class 你的组件Component { imgUrl = imageSrc; }
模板中通过属性绑定引用:
<img [src]="imgUrl" alt="示例图片">
需要确保库的tsconfig.lib.json支持导入非代码文件:
{ "compilerOptions": { "resolveJsonModule": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true }, "include": [ "src/**/*", "node_modules/custom-plugin/assets/**/*.png" ] }
内容的提问来源于stack exchange,提问作者lostintranslation
相关产品推荐
相关产品推荐

