一个 angular 项目之前 sass 用的是 @import 写法,比如:
@import 'node_modules/bootstrap/scss/functions';
build 时会出现下面的 warning
Sass @import rules are deprecated and will be removed in Dart Sass 3.0.0.
改用 @use
@use 'node_modules/bootstrap/scss/functions';
却出现下面的错误:
[ERROR] Undefined mixin.
╷
494 │ @include _assert-ascending($grid-breakpoints, "$grid-breakpoints");
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
╵
node_modules\bootstrap\scss\_variables.scss 494:1
请问如何解决?
在 Angular 项目中,将 Sass 的 @import
语句转换为 @use
时遇到的问题,主要是由于 @use
语法和 @import
语法之间的机制差异。让我们逐步看看如何解决您在转换过程中遇到的警告和错误。
@use
vs. @import
@import
可以导入 Sass 文件并使其作用域中的所有变量、混合和函数在当前文件中可用。
@use
仅能导入指定的模块,默认情况下一切都是私有的。您必须明确指出想要导入的内容。这样避免了命名冲突并提供了更好的模块化。
在使用 @use
时,您需要明确导入内容,这可能是导致Undefined mixin错误的原因。
错误信息的原因:
@use
后,Bootstrap 函数和 mixin 的名称变得更加限定。对于例如 _assert-ascending
等 mixin,必须写成 bootstrap::_assert-ascending()
,其中 bootstrap
是用 @use
指定的命名空间。以下是迁移的正确做法:
将原来的 @import
改为 @use
,并使用命名空间处理:
@use 'node_modules/bootstrap/scss/functions' as *; // 这将使 Bootstrap 的所有 functions 公开
@use 'node_modules/bootstrap/scss/variables' as *; // 同上
在使用Bootstrap中的mixins或functions时,使用 bootstrap
命名空间:
// 使用 mixin
@include bootstrap._assert-ascending($grid-breakpoints, "$grid-breakpoints");
bootstrap
命名空间如果您不想每次都写完整的命名空间,您可以在引入时创建一个别名:
@use 'node_modules/bootstrap/scss/functions' as bf; // 这里设置别名为 bf
@include bf._assert-ascending($grid-breakpoints, "$grid-breakpoints");
假设您原来的 SCSS 文件是这样的:
@import 'node_modules/bootstrap/scss/functions';
// 使用 Bootstrap mixins
@include _assert-ascending($grid-breakpoints, "$grid-breakpoints");
转换后应该是:
@use 'node_modules/bootstrap/scss/functions' as bf;
@use 'node_modules/bootstrap/scss/variables' as bv;
// 使用 Bootstrap mixins
@include bf._assert-ascending($grid-breakpoints, "$grid-breakpoints");
完成以上更改后,尝试重新构建您的 Angular 项目,并观察是否还有相应的警告或错误。
@use
语法进行正确调用。as *
允许所有内容直接访问,需额外注意可能的命名冲突问题。以上就是解决 @use
替换 @import
后遇到问题的方式。如果您还有其他问题或特定错误,请提供更详细的信息,我们可以进一步探讨!
How to disable the Angular v19’s sass compiler deprecation warnings
– dudu 2个月前