webpack项目中样式中的~和script中的@在项目中的区别

样式中的~和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";

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值