Angular 4组件中导入CSS的方法及资源路径访问问题求助
Hey there! I’ve run into this exact problem before with Angular 4, so let’s break down how to get your component accessing those assets properly.
Common Causes & Solutions
1. Double-Check Relative Path Hierarchy
Angular resolves styleUrls paths relative to your component file, so you need to make sure you’re navigating up the directory tree correctly to reach the assets folder.
For example, if your project structure looks like this:
src/ app/ resume/ resume.component.ts assets/ css/ resume-styles.css
Your styleUrls should use a relative path that jumps up two levels from the resume folder to reach src, then into assets:
@Component({ selector: 'app-resume', templateUrl: './resume.component.html', styleUrls: ['../../assets/css/resume-styles.css'] })
Count the ../ segments carefully—each one moves you up one directory level.
2. Use Absolute Paths (With Correct Base Href)
If relative paths feel messy, you can use an absolute path starting with /, but you need to ensure your index.html has the correct <base href> set.
In src/index.html, confirm you have:
<base href="/">
Then your styleUrls can be written as:
styleUrls: ['/assets/css/resume-styles.css']
Angular will resolve this path relative to the base href you’ve defined.
3. Verify angular-cli.json Assets Configuration
Angular 4 uses angular-cli.json (not the newer angular.json) to define which assets get copied to the dist folder during builds. If your assets directory isn’t listed here, the files won’t be available at runtime.
Open angular-cli.json and check the assets array:
"apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", // Make sure this line exists "favicon.ico" ], // ... other configs } ]
If assets is missing, add it and restart your dev server with ng serve.
4. Watch for Typos & Case Sensitivity
It sounds obvious, but double-check:
- Spelling of folder/file names (e.g.,
Assetsvsassets—most OSes are case-sensitive here) - File extensions (e.g.,
.cssvs.scssif you’re using preprocessors)
5. Clear Cache
Sometimes your browser or Angular’s dev server caches old path references. Try:
- Clearing your browser’s cache
- Restarting the dev server with the
--no-cacheflag:ng serve --no-cache
Quick Test
If you’re still stuck, try adding a direct link to your asset in index.html first (e.g., <link rel="stylesheet" href="/assets/css/resume-styles.css">). If that works, the issue is definitely with how your component is resolving the path.
内容的提问来源于stack exchange,提问作者Nam Hồ Thanh

