Angular 4全局样式配置及组件复用样式导入报错求助
First off, your goal is totally achievable—Angular has built-in support for global styles that all components can use without manual imports in each one. Let's break down the right way to set this up, and troubleshoot that import error you ran into.
1. The Recommended Approach: Configure via angular-cli.json
Angular CLI (standard for Angular 4 projects) lets you define global style files directly in its config, so you don't have to import them in every component. Here's how:
- Open your project's root
angular-cli.jsonfile. - Locate the
stylesarray under theappssection. - Add your global style file path here. For example, if your global styles live in
src/styles.css, the config would look like this:"apps": [ { "styles": [ "styles.css", // You can add other global assets here too, like Bootstrap or custom theme files ] } ] - Save the file, then restart your dev server with
ng serve. Now every component in your app will automatically have access to these styles in their templates—no extra imports required!
2. Why Your @import Attempt Failed
That error you saw is almost certainly due to one of these issues:
- Missing file extension: You need to include the full file extension (e.g.,
.css,.scssif using Sass). So the correct import would be@import "../../styles.css";(adjust the path to match your actual file structure). - Incorrect relative path: Double-check the path from your component's style file to the global styles. If your component is in
src/app/my-new-component/and global styles are insrc/styles.css, the relative path should be../../styles.css—but for more reliability, use an absolute path starting fromsrc/if your CLI supports it:@import "~src/styles.css"; - Component encapsulation: By default, Angular components use view encapsulation, which scopes styles to the component itself. Importing a global style inside a component's style file will lock those styles to that component, making them not truly global. That's why the CLI config method is the better choice for universal styles.
3. Alternative: Import in the Root Component
If you don't want to modify the CLI config, you can also add global styles to the root app.component.ts—since it's the parent of all other components, its styles will cascade down:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css', '../styles.css'] // Add global style path here }) export class AppComponent { }
Once you set this up correctly, any new component you create can directly use your global classes in its HTML template without extra setup.
内容的提问来源于stack exchange,提问作者TheCoderGuy

