less / less.js

Less. The dynamic stylesheet language.
http://lesscss.org
Apache License 2.0
17k stars 3.41k forks source link

import styles undefined #4277

Open HuXin957 opened 2 weeks ago

HuXin957 commented 2 weeks ago

To reproduce:

import styles from './index.less';

Current behavior:

const Home = () => {
  console.log(styles) //undefined
  return (
    <div className={styles.main}>
    </div>
  );
};
 {
      test: /\.less$/,
      use: [
        NODE_ENV ? 'style-loader' : MiniCssExtractPlugin.loader,
        'css-loader',
        'postcss-loader',
        {
          loader: 'less-loader',
          options: {
            lessOptions: {
              modules: true,
              javascriptEnabled: true,
            },
          },
        },
      ],
    }

Expected behavior: I hope "className= { styles.main }" can work first, why is that? secondly, how to fix it?

Environment information:

dosubot[bot] commented 2 weeks ago

@HuXin957 Hello there! I'm here to help you with your GitHub issues while waiting for a human maintainer. I'm a bot named Dosu, and I can assist you with bug fixes, answer your questions, and guide you on becoming a contributor.

The issue you're encountering where styles is undefined could be due to a few reasons. Here are some steps to troubleshoot and potentially fix the problem:

  1. CSS Modules Configuration: Ensure that CSS Modules are correctly configured in your css-loader. You need to enable CSS Modules explicitly.

    Update your Webpack configuration to include the modules option in css-loader:

    {
     test: /\.less$/,
     use: [
       NODE_ENV ? 'style-loader' : MiniCssExtractPlugin.loader,
       {
         loader: 'css-loader',
         options: {
           modules: true, // Enable CSS Modules
         },
       },
       'postcss-loader',
       {
         loader: 'less-loader',
         options: {
           lessOptions: {
             javascriptEnabled: true,
           },
         },
       },
     ],
    }
  2. Naming Convention: Ensure that your class names in the Less file follow the correct naming convention. For example:

    .main {
     // styles
    }
  3. File Extension: Make sure the file extension of your Less file is correct and matches the import statement. For example, if your file is named index.less, the import should be:

    import styles from './index.less';
  4. Check for Errors: Look for any errors in the console or terminal that might give more insight into why the styles are not being imported correctly.

If these steps do not resolve the issue, there might be a deeper configuration problem or a compatibility issue with the versions of the tools you are using.

To continue talking to Dosu, mention @dosu.

HuXin957 commented 2 weeks ago

first,thanks. but, that can't solve my problem