Angular.io 指出:
主 CLI 配置文件 angular.json,[...] 允许您替换any file具有该文件的特定于目标的版本。
这实际上是愿景,但根据这个 GitHub 线程 https://github.com/angular/angular-cli/issues/11451,目前情况并非如此。
到目前为止看来,只有.ts
and .html
文件受支持。
因此,目前问题的答案是否定的,目前还无法替换 SCSS 文件。
2021 年 1 月更新:还是不行。测试用角11.0.9.
TLDR:
-
如果您尝试使用文件替换功能,Angular 11.x 现在会在不支持的文件类型上出现错误
(下面描述的解决方法仍然有效,因为它不使用文件替换功能)
-
它仅支持以下类型的文件替换:.cjs
, .js
, .json
, .mjs
and, .ts
背景:
文档中支持所有文件类型的最初声明似乎是错误的。 Angular 11 引入了一项检查,以检查不支持的文件类型。
修复(@Angular-devkit/build-Angular):向 fileReplacement 添加验证... https://github.com/angular/angular-cli/commit/424af2860260b9e19df9d82940b9f088ea474b95
fileReplacement 的目的是用构建中的其他编译源文件替换编译源文件(JavaScript 或 TypeScript)。通过此更改,我们添加了验证,以便在文件具有不受支持的扩展名时使构建失败。
因此,Angular 11 改变了两件事。首先你必须使用src
and replaceWith
代替replace
and with
。虽然这没有帮助,因为你会得到Data path ".fileReplacements[1].replace" should match pattern "\.(([cm]?j|t)sx?|json)$".
,如果你使用不支持的文件类型 https://regex101.com/r/bjukt4/1 like .scss
.
2020 年 2 月更新: 还是不行。测试用角9.0.0.
但有一个解决方法:
您可以使用不同的配置angular.json
实现相同的目标 - 替换 SCSS 文件。
文件夹结构:
src/
scss/
default/
_scss-config.scss
special/
_scss-config.scss
src/scss/default/scss-config.scss
body { background-color: blue; }
src/scss/special/scss-config.scss
body { background-color: red; }
角度.json
<!-- language: lang-json -->
{
[...]
"architect": {
"build": {
"options": {
"stylePreprocessorOptions": {
"includePaths": [
"src/scss/default"
]
}
},
"configurations": {
"default": {
"stylePreprocessorOptions": {
"includePaths": [
"src/scss/default/"
]
}
},
"special": {
"stylePreprocessorOptions": {
"includePaths": [
"src/scss/special/"
]
}
}
}
},
"serve": {
"configurations": {
"default": {
"browserTarget": "angular-scss-replacement:build:default"
},
"special": {
"browserTarget": "angular-scss-replacement:build:special"
}
}
}
[...]
}
}
style.scss 或 component.scss
@import 'scss-config';
/* use your SCSS variables and stuff as you normally would */
请注意,您不得包含_
(下划线)来自导入语句中的文件名
(有关更多详细信息,请阅读部分 https://sass-lang.com/guide)
如何使用它:
// 'ng serve'-command uses default configuration as defined in angular.json > build
ng serve
// default config creates blue background
ng serve --configuration=default
// specail config create red background
ng serve -c=special
(这个解决方案来自上面提到的线程 - 谢谢理查德特雷尔 https://github.com/angular/angular-cli/issues/11451#issuecomment-424715627)
这种方法的缺点:
- 它强制您使用特定的文件夹结构来分隔不同的 SCSS 配置
- 它可能会迫使您将这些文件夹移出正常的文件夹结构。
例如,"includePaths": ["src/scss"]
不适用于上述文件夹结构,因为 SCSS 配置无法单独加载。