Study notes-how react configures sass globally


In react, under the src folder, create a new assets folder, which stores some public scss files. When the component needs to use the scss file, it needs to be imported with @import in the style of the component. Due to the frequent use of public scss files, you need to use @import to import each time. This will be very troublesome. The code should be more elegant. In order to achieve this goal, the public scss file needs to be globally configured, so that when the component is used, it does not need to be imported.

1. Download the necessary packages: 

This project requires three packages, sass-resources-loader, customize-cra, and react-app-rewired, which can be used for yarn add or npm install + package name download.

yarn add sass-resources-loader
yarn add customize-cra
yarn add react-app-rewired

 2. Configure the new file:

In the root directory of the project, create a new file named config-overrides.js and configure it in the file so that the project can modify its configuration without exposing the webpack.config.js file.

// 使用sass作为全局变量
const { override, adjustStyleLoaders }  = require("customize-cra");

module.exports = override(
        // 配置指定文件为sass全局文件,可以不用导入就可以使用
        adjustStyleLoaders(rule => {
                if (rule.test.toString().includes('scss')) {
                        rule.use.push({
                                loader: require.resolve('sass-resources-loader'),
                                options: {
                                        resources: [
                                                './src/assets/_vars.scss',
                                                './src/assets/_mixin.scss',
                                                './src/assets/_func.scss',
                                                './src/assets/_public.scss'
                                        ]
                                }
                        });
                }
        })
);

 The resources node is the scss file that needs to be configured globally.

3. Modify the package.json file:

 If you want the global configuration of sass to take effect, you need to modify the package.json file before restarting the project.

"scripts": {
		"start": "set PORT=8888&&react-app-rewired start",
		"build": "react-app-rewired build",
		"test": "react-app-rewired test",
		"eject": "react-app-rewired eject"
	},

 After everything is configured, the variables and functions declared in the public scss file can be used in the scss file of any component. No need to introduce.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109484010