Angular 2 URL分隔符缺失及依赖包复用组件图片不显示问题
Let's work through resolving your image display and URL separator problems step by step:
1. Fix the URL Separator Problem
Angular (and web development in general) relies on forward slashes (/) for file paths—backslashes (\) are Windows filesystem-specific and will break path resolution in the browser.
Update your SCSS file to use forward slashes:
.test { background-image: url('../assets/images/sampleImage.png'); }
2. Ensure Library Assets Are Properly Packaged
When building a reusable Angular library like UI-Common, its assets aren’t automatically included in the main application’s build unless you explicitly configure this. Here’s how to fix that:
Step 2.1: Configure Library Asset Copy
In your UI-Common library’s ng-package.json (located in the library root), add an assets array to specify which assets should be copied to the library’s dist folder during build:
{ "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", "dest": "../../dist/ui-common", "lib": { "entryFile": "src/public-api.ts" }, "assets": [ "./src/assets/images" ] }
This tells ng-packagr to copy your library’s src/assets/images folder to dist/ui-common/assets/images when building.
Step 2.2: Rebuild the Library
After updating the config, rebuild your UI-Common library to apply the changes:
ng build ui-common
3. Adjust the Asset Path in Your Component
With the library’s assets properly packaged, you need to ensure the path in your SCSS resolves correctly from the main application. Try one of these approaches:
Option A: Use an Absolute Path Relative to the Main App
If your main app serves library assets from assets/ui-common, adjust the path like this:
.test { background-image: url('/assets/ui-common/images/sampleImage.png'); }
Option B: Use a Library Reference Path
If you’re using an Angular workspace, you can reference the library’s assets directly using the ~ alias (this may require additional path resolution setup in your main app’s config):
.test { background-image: url('~ui-common/assets/images/sampleImage.png'); }
4. Verify Main App Configuration (Optional)
If issues persist, check your main app’s angular.json to ensure it imports the library’s assets correctly. Add this to your main app’s assets array:
{ "projects": { "base-common": { "architect": { "build": { "options": { "assets": [ "src/favicon.ico", "src/assets", { "glob": "**/*", "input": "./node_modules/ui-common/assets", "output": "/assets/ui-common/" } ] } } } } } }
This copies the library’s assets from node_modules/ui-common/assets to the main app’s assets/ui-common folder during build, making them accessible via the absolute path in Option A.
Following these steps should resolve both the image loading issue and the URL separator problem.
内容的提问来源于stack exchange,提问作者Praveen Kumar

