配置less
安装less-loader
yarn add less-loader
打开 webpack.config.dev.js 和 webpack.config.prod.js
找到 test: /.css$/, 修改为 test: /.(css|less)$/,
找到 text 字段下的 use ,给use数组在添加一个对象 { loader: require.resolve('less-loader')}
重启服务
启用css作用域(css只对本页面生效)
打开 webpack.config.dev.js 和 webpack.config.prod.js
找到 loader: require.resolve('css-loader') 下的 options 字段, 给这个对象新增一个字段 modules: true
页面调用
import style from './style.less'
console.log(style) // class名均为style对象的key,所以调用必须使用style.App
render() {return ( <div className={style.App}> </div> ) }
重启服务 & 查看效果
px转换成rem
安装 postcss-px2rem
yarn add postcss-px2rem
打开 webpack.config.dev.js 和 webpack.config.prod.js
// 调用postcss-px2rem const px2rem = require('postcss-px2rem')
在css-loader中找到 autoprefixer 这个属性,在这个属性之后添加 px2rem({ remUnit: 75 })
autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9' // React doesn't support IE8 anyway ], flexbox: 'no-2009' }), px2rem({ remUnit: 75 })
重启服务 & 查看效果
附 : 完整代码
webpack.config.dev.js
// webpack.config.dev.js { test: /.(css|less)$/, use: [ require.resolve('style-loader'), { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true // 是否启动css局部作用域 } }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9' // React doesn't support IE8 anyway ], flexbox: 'no-2009' }), px2rem({ remUnit: 75 }) //设计稿根据750px(iphone6) ] } }, { loader: require.resolve('less-loader') } ] },
webpack.config.prod.js
// webpack.config.prod.js { test: /.(css|less)$/, loader: ExtractTextPlugin.extract( Object.assign( { fallback: { loader: require.resolve('style-loader'), options: { hmr: false } }, use: [ { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, // 是否启动css局部作用域 minimize: true, sourceMap: shouldUseSourceMap } }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9' // React doesn't support IE8 anyway ], flexbox: 'no-2009' }), px2rem({ remUnit: 75 }) //设计稿根据750px(iphone6) ] } }, { loader: require.resolve('less-loader') } ] }, extractTextPluginOptions ) ) // Note: this won't work without `new ExtractTextPlugin()` in `plugins`. },
style.less
.App { text-align: center; font-size: 16px; .goto { color: red; } }
App.vue
// 页面调用 import style from './style.less' // console.log(style) 输出:{App:{...},goto:{...}} <div className={style.App}> <Link to="/series" className={style.goto}> 跳转 </Link> </div>