【前言】
無論是vue還是react的css模塊化解決方案都是依賴loader來實(shí)現(xiàn)的 在使用上,vue中用scoped屬性實(shí)現(xiàn)樣式的私有化,利用深度作用選擇器/deep來實(shí)現(xiàn)樣式的去私有化。
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< 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):
1
2
3
4
5
6
7
8
9
|
//test.less .demo { height : 100px ; padding-top : 20px ; background-color : grey; :global(.child) { color : red } } |
1
2
3
4
5
6
7
|
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)容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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自帶的那套。
完
以上就是如何在vue-cli中使用css-loader實(shí)現(xiàn)css module的詳細(xì)內(nèi)容,更多關(guān)于vue-cli中使用css-loader實(shí)現(xiàn)css module的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://juejin.cn/post/6914489741979156487