react create-react-app deployment less

Environmental information:

create-react-app:v5
react:18.2.0
node:18.16.0
If you don't have to use less, it is recommended to use scss directly.
Because less configuration will encounter many problems.

Configure less process:

If you only need sass, you can use sass directly. Because scss is configured by default.
npm, yarn, cnpm, pnpm are all fine

npm install node-sass sass-loader --save-dev

After my troubles, I recommend the third way to use the create-react-app v5 version! That is, use customize-cra-5!

Method 1: npm run eject method

This method is to run npm run eject to expose the webpack configuration, and then configure it. This exposure is irreversible !
For specific methods, refer to:
Less configuration guide
to create a React project + TS from 0 to 1 (1) Create the project, configure less, register less globally, and configure aliases

Method 2: Do not expose webpack configuration

Method 1: Use @craco/craco

The related configuration of less is introduced in create-react-app and CSS Modules uses
the configuration in create-react-app to support less.

Method 2: Use react-app-rewired and customize-cra

1. Run

npm install react-app-rewired customize-cra --save-dev
npm install less less-loader --save-dev

2. Create a config-overrides.js file in the project root directory
and introduce addLessLoader. This is the API for adding less.
The specific API documentation is as follows:
customize-cra/api.md
Insert image description here

const {
    
     override, addLessLoader, addPostcssPlugins } = require("customize-cra");

module.exports = override(
  addLessLoader({
    
      
    lessOptions:{
    
    
      javascriptEnabled: true,  
      modifyVars: {
    
     '@primary-color': '#1DA57A' }, // 你的主题色  
    },
  }) 
);

It should be noted here that different writing methods need to be used according to different versions of less-loader, because the latest version of the API has changed.
This is the way it is written in the above document, and the attributes are written directly. And mine wraps a layer of lessOptions. If you use the above to report an API mismatch, you can try this.

const {
    
     addLessLoader } = require("customize-cra");

module.exports = override(
  addLessLoader({
    
    
    strictMath: true,
    noIeCompat: true,
    modifyVars: {
    
    
      "@primary-color": "#1DA57A", // for example, you use Ant Design to change theme color.
    },
    cssLoaderOptions: {
    
    }, // .less file used css-loader option, not all CSS file.
    cssModules: {
    
    
      localIdentName: "[path][name]__[local]--[hash:base64:5]", // if you use CSS Modules, and custom `localIdentName`, default is '[local]--[hash:base64:5]'.
    },
  })
);

Adjust the less configuration structure according to the version
Breaking change: css-loader@^3.0.0 (+addLessLoader)
Insert image description here

3. Modify the scripts configuration in package.json

 "scripts": {
    
    
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },

4. Modify the suffix name of App.css to less, and also modify the import './index.less'; when introduced in index.js;

5. When you run npm start, you will find an error
(1.) Invalid options object. PostCSS Loader has been initialized using an options object that does not match the API schema.
This error is caused by the postcss-loader version being too high and the framework itself. There is a conflict in webpack configuration.
The solution is to downgrade:

run

cnpm uninstall postcss-loader

Then download the lower version of the loader

cnpm install [email protected]
Module build failed (from ./node_modules/.store/[email protected]/node_modules/postcss-loader/dist/cjs.js):
ValidationError: Invalid options object. PostCSS Loader has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'plugins'. These properties are valid:
   object {
    
     postcssOptions?, execute?, sourceMap?, implementation? }

Invalid options object. PostCSS Loader has been initialized using an options object that does not match the API schema.

(2).Error: PostCSS plugin postcss-normalize requires PostCSS 8.
降低postcss-normalize
Error: PostCSS plugin postcss-flexbugs-fixes requires PostCSS 8.
降低postcss-flexbugs-fixes 版本
Error: PostCSS plugin postcss-normalize requires PostCSS 8 error screenshot

Module build failed (from ./node_modules/postcss-loader/src/index.js):
TypeError: plugin is not a function
TypeError: plugin is not a function error screenshot

Wait, these are all caused by postcss and postcss-loader, so if you encounter them, just lower the version. Below is my version configuration:

```javascript
   "postcss": "^4.1.16",
    "postcss-flexbugs-fixes": "^4.2.1",
    "postcss-loader": "^2.0.0",
    "postcss-normalize": "^4.0.0",
    "postcss-preset-env": "^9.1.4",
    ```

Method 3: Use customize-cra-5

Same as the second step, just replace customize-cra with customize-cra-5

yarn add customize-cra-5 react-app-rewired --dev

npm customize-cra-5 homepage screenshot
Then the writing method remains the same, and there is no need to lower the less-loader version! ! ! !

Summarize:

Exposing eject will be relatively simple to configure and there won't be so many problems.
However, many people do not want to expose eject because it is irreversible, and will choose to use a plug-in to overwrite the original configuration react-app-rewired and customize-cra. For the v5 version, please use customize-cra-5. There are still many people using it (I will This method is recommended).

How you choose depends entirely on your needs! You can even use less and use scss directly.

SCSS and LESS are both preprocessing languages ​​for CSS. They both extend the CSS language and provide more features, but there are still some differences between them.

the difference:

1. Variable: In SCSS, use $ as variable identifier, while in LESS, use @ as variable identifier.
2. Nesting: SCSS supports CSS nesting rules, but LESS does not.

Functions and mixins: Both SCSS and LESS support functions and mixins, but they are used in different ways. SCSS uses @mixin and @include to define and reference mixes, while LESS uses .mixin() and .include(). In addition, SCSS function names start with /, while LESS uses ~ or ::.
Output settings: SCSS provides 4 output options: nested, compact, compressed and expanded, while LESS does not provide output settings.
Conditional statements: SCSS supports conditional statements, you can use if{}else{}, for{} loops, etc., but LESS does not support it.
scenes to be used:

SCSS is better suited for larger projects as it is better organized and maintainable while supporting more advanced features such as nesting, functions, mixins, and conditional statements. LESS is more suitable for simple style sheets or situations where CSS needs to be dynamically generated because it is simple and easy to use, extends the CSS language, and provides more convenient features such as variables, mixins, and functions.

In most cases, both scss and less are fine, just choose one.

Supplement: How to use cssModules

We used less above, but if we want to achieve modularity, we have to change the file name and introduction method.
As shown below:
App.less is changed to App.module.less
App.js introduction is changed to import styles from './App.module.less';
Code screenshot
Then you can use styles.xx. The effect is that it will automatically add a random one. String to prevent class name conflicts!
css modules screenshot

The same is true for scss. Just change the above steps to scss.

For other configurations, please refer to this: react create-react-app v5 to build the project from scratch

Guess you like

Origin blog.csdn.net/weixin_44058725/article/details/133267926