在vue-cli中使用css-loader實(shí)現(xiàn)css module
【前言】
無論是vue還是react的css模塊化解決方案都是依賴loader來實(shí)現(xiàn)的在使用上,vue中用scoped屬性實(shí)現(xiàn)樣式的私有化,利用深度作用選擇器/deep來實(shí)現(xiàn)樣式的去私有化。
例子:
<div>
<div class="demo">
<div class="child"></
div>
</div>
</div>
<script>
// some code
<script/>
<style lang="less" scoped>
.demo {
height: 100px;
padding-top: 20px;
background-color: grey;
/deep/.child {
color: red;
}
}
</style>
在react中使用上是這么搞的(基于css-loader):
//test.less
.demo {
height: 100px;
padding-top: 20px;
background-color: grey;
:global(.child) {
color: red
}
}
import styles from './test.less'
// some code
<div className={styles.demo}>
<div class="child"></div>
</div>
不得不說,在使用上還是vue比較方便。
如果硬要在vue中使用css-loader實(shí)現(xiàn)css module的這套解決方案呢?這里以vue-clie 3.x為例。
無論在vue的腳手架vue-cli中還是在react的腳手架umi中,,現(xiàn)在都使用了webpack-chain來實(shí)現(xiàn)配置webpack.
這里在vue-cli腳手架創(chuàng)建的項(xiàng)目根目錄下,新建vue.config.js,并寫入如下內(nèi)容:
module.exports = {
chainWebpack: (config) => {
config.devServer
.proxy({
'/api': {
target: 'http://localhost:3000',
pathRewrite: { '^/api': '', },
},
})
.port(9000);
config.module
.rule('less')
.oneOf('normal-modules')
.test(/.less$/)
.use('css-loader')
.tap(options => {
return Object.assign(options, {
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]',
auto: /\.less$/i,
},
})
});
},
};
本來其實(shí)也不用寫這段內(nèi)容,默認(rèn)情況,vue-cli的腳手架已經(jīng)配置了css-loader的模塊化,但是需要把less文件命名成xxx.module.less的形式,這和umi那套不同,也不方便,這樣配置然后重啟,就能像react一樣寫css了,另外把引入的style存入data中。這里只是說下可以在vue-cli使用css-loader的那套解決方案,但最佳實(shí)踐還是用vue自帶的那套。
到此這篇關(guān)于在vue-cli中使用css-loader實(shí)現(xiàn)css module的文章就介紹到這了,更多相關(guān)vue-cli使用css module內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章
css 命名:BEM, scoped css, css modules 與 css-in-js詳解
這篇文章主要介紹了css 命名:BEM, scoped css, css modules 與 css-in-js的相關(guān)知識,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,,需要的朋友2020-08-24使用Loader.css和css-spinners來制作加載動畫的方法
這篇文章主要介紹了使用Loader.css和css-spinners來制作加載動畫的方法,基本上使用純CSS就可以實(shí)現(xiàn),簡單高效,需要的朋友可以參考下2016-04-05CSS3制作ajax loader icon實(shí)現(xiàn)思路及代碼
用到了兩個CSS3屬性transform、animation,實(shí)現(xiàn)原理為:transform控制每個小方塊在Y軸的偏移,rotate控制旋轉(zhuǎn)的角度,scale縮放至原大小的一半,具體祥看下文,希望對大家2013-08-25

