• REACT项目LESS样式无效


     

    我们在用react脚手架搭建项目的时候,webpack的相关配置已经被隐藏了。如果要解决less样式无效这个问题,那么我们需要先把webpack的相关配置暴露出来。

    先贴一下我react和webpack的版本,因为我在查资料的时候发现config最后暴露出来的文件和网上的不一样。

    1、安装less依赖

    1 npm install less less-loader

    2、暴露配置:

    1 npm run eject

    3、修改配置文件


    经过第二步之后,你的项目会多一个config的文件夹,里面的内容如上图。

    然后需改一下webpack.config.js即可。

    (1)在47行左右添加lessRegex 和lessModuleRegex ,参考上面的cssRegex和cssModuleRegex

    1 // style files regexes
    2 const cssRegex = /.css$/;
    3 const cssModuleRegex = /.module.css$/;
    4 const sassRegex = /.(scss|sass)$/;
    5 const sassModuleRegex = /.module.(scss|sass)$/;
    6 const lessRegex = /.less$/;
    7 const lessModuleRegex = /.module.less$/;

    (2)在73行左右添加一个loader

     1   const getStyleLoaders = (cssOptions, preProcessor) => {
     2     const loaders = [
     3       isEnvDevelopment && require.resolve('style-loader'),
     4       isEnvProduction && {
     5         loader: MiniCssExtractPlugin.loader,
     6         // css is located in `static/css`, use '../../' to locate index.html folder
     7         // in production `paths.publicUrlOrPath` can be a relative path
     8         options: paths.publicUrlOrPath.startsWith('.')
     9           ? { publicPath: '../../' }
    10           : {},
    11       },
    12       {
    13         loader: require.resolve('css-loader'),
    14         options: cssOptions,
    15       },
    16       {
    17         loader: require.resolve('less-loader')
    18       }

    图中的最后一个大括号的内容。

    (3)、在326行左右你会看到一个module,里面有strictExportPresence,rules等参数。再配置两个关于less的参数即可。参照463行左右的sassRegex和sassModuleRegex。

     1  {
     2      test: lessRegex,
     3      exclude: lessModuleRegex,
     4      use: getStyleLoaders(
     5        {
     6          importLoaders: 3,
     7          sourceMap: isEnvProduction && shouldUseSourceMap,
     8        },
     9        'less-loader'
    10      ),
    11      sideEffects: true,
    12    },
    13 
    14    {
    15      test: lessModuleRegex,
    16      use: getStyleLoaders(
    17        {
    18          importLoaders: 3,
    19          sourceMap: isEnvProduction && shouldUseSourceMap,
    20          modules: {
    21            getLocalIdent: getCSSModuleLocalIdent,
    22          },
    23        },
    24        'less-loader'
    25      ),
    26    },

    最后重启项目,然后坐等Compiled successfully!的提示就好了。

  • 相关阅读:
    Python 生成器
    Python 装饰器
    Go语言【第十四篇】:Go语言基础总结
    Go语言【第十三篇】:Go语言递归函数
    Go语言【第十二篇】:Go数据结构之:切片(Slice)、范围(Range)、集合(Map)
    Go语言【第十一篇】:Go数据结构之:结构体
    Java入门之:对象和类
    Alpha阶段第2周/共2周 Scrum立会报告+燃尽图 04
    Alpha阶段第2周/共2周 Scrum立会报告+燃尽图 03
    Alpha阶段第2周/共2周 Scrum立会报告+燃尽图 02
  • 原文地址:https://www.cnblogs.com/jackal1234/p/15114534.html
Copyright © 2020-2023  润新知