如何通过Angular CLI打包工具为组件导入ngx-bootstrap的bs-datepicker.css?
Got it, let's sort out why your style import isn't working and get that datepicker styled properly. The core issue is that Angular CLI resolves paths in a component's styleUrls relative to the component file itself—so your direct node_modules path isn't being resolved correctly. Here are the most reliable solutions:
1. Global Import (Recommended for Project-Wide Use)
This is the easiest approach if you'll be using the datepicker across multiple components. Open your project's root angular.json file, find the build > options > styles array, and add the CSS path there:
"styles": [ "src/styles.css", "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css" ]
After making this change, restart ng serve to apply the new configuration. This will bundle the datepicker styles globally, so every component in your app will have access to them.
2. Component-Specific Import via @import
If you only need the datepicker styles in one component, skip the global setup and use @import directly in the component's style file (e.g., your-component.component.scss):
// For older Angular CLI versions, use the ~ prefix to target node_modules @import "~ngx-bootstrap/datepicker/bs-datepicker.css"; // For newer Angular CLI versions (v12+), you can omit the ~ @import "ngx-bootstrap/datepicker/bs-datepicker.css";
This tells the build tool to pull the styles from the node_modules directory and scope them to just this component.
3. Adjust styleUrls with Relative Paths (Not Recommended)
If you really want to use styleUrls, you'll need to write a relative path from your component file to the node_modules directory. For example, if your component lives at src/app/feature/components/my-datepicker/, the path would look like this:
@Component({ selector: 'app-my-datepicker', templateUrl: './my-datepicker.component.html', styleUrls: [ './my-datepicker.component.css', '../../../../node_modules/ngx-bootstrap/datepicker/bs-datepicker.css' ] })
This is fragile though—if you move your component to a different directory, you'll have to update the path again. Stick with the first two methods for better maintainability.
Quick Check
Before trying any of these, double-check that the file actually exists at node_modules/ngx-bootstrap/datepicker/bs-datepicker.css—sometimes package versions can change file structures, so confirm the path matches your installed ngx-bootstrap version.
内容的提问来源于stack exchange,提问作者Guilherme Nass

