create-react-app 使用Less(less)

2019-02-28  本文已影响3人  王阿觉

先创建项目,yarn create react-app you-demo
cd you-demo
yarn start

然后使用git 命令,(重要的一个步骤,不然后面会容易报错)
git .add 添加当前文件到git
git commit -m "init" 提交一个初始化的commit文件

接着安装less

yarn add less less-loader

再使用yarn eject 暴露webpack配置文件
由于新版本中已经部分开发与生产环境,所以只有一个配置文件
在 webpack.config.js中仿照官方配置的css和sass配置文件,使用eject后在config/webpack.config.js中去找配置文件,英文很多,但是别怕,都是有套路的。慢慢找找。

css的配置地方.png
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

然后我们找到sass的配置,复制一版,
sass-loader改为less-loader

目录文件.png 仿照Sass改一版就好
  {
                            test: lessRegex,
                            exclude: sassModuleRegex,
                            use: getStyleLoaders(
                                {
                                    importLoaders: 2,
                                    sourceMap: isEnvProduction
                                        ? shouldUseSourceMap
                                        : isEnvDevelopment,
                                },
                                'less-loader'
                            ),
                            // Don't consider CSS imports dead code even if the
                            // containing package claims to have no side effects.
                            // Remove this when webpack adds a warning or an error for this.
                            // See https://github.com/webpack/webpack/issues/6571
                            sideEffects: true,
                        },
                        // Adds support for CSS Modules, but using LESS
                        // using the extension .module.scss or .module.less
                        {
                            test: lessModuleRegex,
                            use: getStyleLoaders(
                                {
                                    importLoaders: 2,
                                    sourceMap: isEnvProduction
                                        ? shouldUseSourceMap
                                        : isEnvDevelopment,
                                    modules: true,
                                    getLocalIdent: getCSSModuleLocalIdent,
                                },
                                'less-loader'
                            ),
                        },

修改后保存,重启一下 yarn start ,然后就阔以愉快的用Less编写了
有一点需要注意的地方是,即使是同级目录,
引用import './demo.less',中的时候,一定要加上./否则会编译报错。
最近在学习React大家一起进步呀~

上一篇 下一篇

猜你喜欢

热点阅读