在Angular 14中,你可以将CSS文件与库组件一起打包并发布到NPM。要达到这个目的,需要按照以下步骤:
在库组件文件夹中创建CSS文件。这里我们创建一个名为“my-component.css”的文件。
在组件TS文件中导入CSS文件:
import { Component } from '@angular/core';
import './my-component.css';
@Component({
selector: 'my-component',
templateUrl: './my-component.html'
})
export class MyComponent {
// ...
}
或者
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent implements OnInit {
constructor() { }
ngOnInit() { }
}
要注意的是,如果你使用第一种方法导入CSS文件,则必须将CSS文件的路径放在字符串中。
"architect": {
"build": {
"options": {
// ...
"styles": [
"src/styles.css",
"node_modules/some-library/styles.css",
"projects/my-library/src/lib/my-component.css" // 添加的这一行
],
// ...
}
// ...
}
// ...
}
这样做后,打包时你的CSS文件就会自动包含在库组件中。现在你可以发布你的库到NPM,并且CSS文件也会一起发布。
注意:如果你修改了库中的CSS文件,则必须手动重新打包和发布库。