Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

create-react-app 添加less文件后,组件会把所有的less文件都引入,如何只引入自己的less?

最近再用create-react-app+antd搭建,在webpack添加了less的支持,但是发现组件A会把其它组件的less文件自动引入,组件代码写的是引入自己的less文件,这是什么情况?
image.png

18b847f9ac56fef16cc84173faceba0.png

webpack配置如下:

{
            test: /.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              plugins: [
                ['import', [{ libraryName: 'antd', style: true }]],  // import less
              ],
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
            },
          },
          
          
          {
            test: /.less$/,
           
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                 
                },
              },
              {
                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',
                    }),
                  ],
                },
              },
              {
                loader:require.resolve('less-loader'),
                options: {
                  modules: true,
                  modifyVars: {
                      "@primary-color": "#3297fd"
                  }
                }
              }
            ],
          },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
.test {
    font-size: "20px"
}
import style form "style.less"

<div style={style.test}></div>

使用这种方式,不要直接在组件引入整个样式文件


不好意思,手快一下写错。
正确写法:

import style form "style.less"

<div className={style.test}></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...