样式中的~和script中的@在项目中的区别
在项目的单组件文件中经常可以看到这两种模块引入方式:
import LogoSvg from '@src/components/svg-icon/LogoSvg';
@import "~@src/css/variables.less";
可以发现两者有些许不同:在less中前面加了一个波浪号,而在script中没有。那么两者的区别在哪里呢?
webpack别名配置
我们知道之所以能够在项目中使用@是因为在webpack中配置了别名,所以在打包时webpack会将我们的@或者~替换成正确的路径。比如:
resolve: {
extensions: ['.ts', '.tsx', '.js', '.vue'],
alias: {
'~': path.join(__dirname, SrcDirPath),
'@': path.join(__dirname, SrcDirPath), // 方便css以绝对路径的形式引入
}
},
通常来说,按照webpack的别名配置,在less中这样import其他模块照理说是行的通的,然而事实却不是。
CSS Loader
对于样式的打包,项目采用了style-loader、css-loader以及less-loader等。在解析时css-loader会把把非根路径的url解释为相对路径, 加~前缀才会解释成模块路径。
所以需要加上"~"前缀。
Less Loader
以下引用至less loader的文档。
webpack resolver
webpack provides an advanced mechanism to resolve files. The less-loader
applies a Less plugin that passes all queries to the webpack resolver. Thus you can import your Less modules from node_modules
. Just prepend them with a ~
which tells webpack to look up the modules
.
@import '~bootstrap/less/bootstrap';
It’s important to only prepend it with ~
, because ~/
resolves to the home-directory. webpack needs to distinguish between bootstrap
and ~bootstrap
, because CSS and Less files have no special syntax for importing relative files. Writing @import "file"
is the same as @import "./file";