How to solve the problem of react official scaffolding does not support less

Source: Internet
Author: User
Tags postcss
Say in front


Create-react-app is the best way to build a new react single-page application that is provided by react and is recommended, but the dynamic style language less is not supported by default in the current version (1.5.x) of the projects it builds. If we have to use less for our project, we need to integrate it manually. This article focuses on the integration process to make a summary record.


Environment preparation


This section first uses Create-react-app to build a new react project as an experimental environment.



If you have not used Create-react-app before, please install it globally (assuming that you have node. js already installed) by using the following command:


npm install -g create-react-app


Then, build a new project with the following commandmy-app:


npx create-react-app my-app


Thecd my-applab environment is ready by command to enter the project folder, execute theyarn startcommand launcher, and run successfully.



Final Project structure:


┌─node_modules ├─public├─src           ├─.gitignore├─package.json├─README.md└─yarn.lock
Install Less & Less-loader


To make Create-react-app build a project that can parse less files properly, just let webpack compile less files into CSS files.



So, the first thing to do is to add the less and Less-loader to the project:


yarn add less less-loader


So it's OK? The above only installs less and Less-loader in the project, but has not yet used less-loader through Webpack.



As for how to use? How many kinds of use? Please refer to the Webpack documentation, which is not described here.



Assuming you have read the above Webpack documentation carefully, you also know that we should choose towebpack.config.jsconfigure Less-loader in the file.


Exposing Webpack configuration Files


Suddenly, you will find that Webpack related profiles are not found in our lab project.



Because scaffolding in order to implement the "0 configuration", some common scripts and configurations are integrated into the react-scripts by default, so that we can focus onsrcthe development work under the directory and no longer worry about the environment configuration. At the same time, the scripts and configurations that are integrated are also removed from the program directory, and the program directory becomes much cleaner.



What if we want to customize the environment configuration?



Once the project is built, a command is provided thatyarn ejectallows us to expose the configuration and scripts that are react-scripts integrated.



The following is ayarn ejectdescription of the scaffolding command:


Yarn Eject
Removes this tool and copies build dependencies, configuration files and scripts into the app directory. You can ' t go back!


Presumably, after executing the command, the built dependencies, configuration files, and scripts are copied to the program directory. The operation is irreversible, and the command is removed after execution, meaning it can only be executed once.



As for what the react-scripts integrates,yarn ejectit can be seen by the execution record of the command:


λ yarn eject
yarn run v1.6.0
$ react-scripts eject
? Are you sure you want to eject? This action is permanent. Yes
Ejecting...

Copying files into E:\React\my-app
  Adding \config\env.js to the project
  Adding \config\paths.js to the project
  Adding \config\polyfills.js to the project
  Adding \config\webpack.config.dev.js to the project
  Adding \config\webpack.config.prod.js to the project
  Adding \config\webpackDevServer.config.js to the project
  Adding \config\jest\cssTransform.js to the project
  Adding \config\jest\fileTransform.js to the project
  Adding \scripts\build.js to the project
  Adding \scripts\start.js to the project
  Adding \scripts\test.js to the project

Updating the dependencies
  Removing react-scripts from dependencies
  Adding autoprefixer to dependencies
  Adding babel-core to dependencies
  Adding babel-eslint to dependencies
  Adding babel-jest to dependencies
  Adding babel-loader to dependencies
  Adding babel-preset-react-app to dependencies
  Adding babel-runtime to dependencies
  Adding case-sensitive-paths-webpack-plugin to dependencies
  Adding chalk to dependencies
  Adding css-loader to dependencies
  Adding dotenv to dependencies
  Adding dotenv-expand to dependencies
  Adding eslint to dependencies
  Adding eslint-config-react-app to dependencies
  Adding eslint-loader to dependencies
  Adding eslint-plugin-flowtype to dependencies
  Adding eslint-plugin-import to dependencies
  Adding eslint-plugin-jsx-a11y to dependencies
  Adding eslint-plugin-react to dependencies
  Adding extract-text-webpack-plugin to dependencies
  Adding file-loader to dependencies
  Adding fs-extra to dependencies
  Adding html-webpack-plugin to dependencies
  Adding jest to dependencies
  Adding object-assign to dependencies
  Adding postcss-flexbugs-fixes to dependencies
  Adding postcss-loader to dependencies
  Adding promise to dependencies
  Adding raf to dependencies
  Adding react-dev-utils to dependencies
  Adding resolve to dependencies
  Adding style-loader to dependencies
  Adding sw-precache-webpack-plugin to dependencies
  Adding url-loader to dependencies
  Adding webpack to dependencies
  Adding webpack-dev-server to dependencies
  Adding webpack-manifest-plugin to dependencies
  Adding whatwg-fetch to dependencies

Updating the scripts
  Replacing "react-scripts start" with "node scripts/start.js"
  Replacing "react-scripts build" with "node scripts/build.js"
  Replacing "react-scripts test" with "node scripts/test.js"

Configuring package.json
  Adding Jest configuration
  Adding Babel preset
  Adding ESLint configuration

Ejected successfully!

Please consider sharing why you ejected in this survey:
  http://goo.gl/forms/Bi6CZjk1EqsdelXk1

Done in 5.37s.


Having said so much, how can we expose webpack profiles in our projects now? Yes, you're right, you just need to run a little bityarn eject.



Then look at the catalogue of our experimental items, and you will find one moreconfigfolder with three configuration files on Webpack:


Webpack.config.dev.js # Development Environment Configuration
Webpack.config.prod.js # production environment configuration
webpackDevServer.config.js # development server configuration


What we need to focus on is the top two, and the last one ishttp://localhost:3000some of the relevant configurations for the local development server.


Modifying the Webpack configuration


In theory, you need to synchronize the modificationswebpack.config.dev.jsandwebpack.config.prod.jsconfiguration files:



module.rulesFind the load rule for the CSS file in the node:


    1. test: /\.css$/modified totest: /\.(css|less)$/;
    2. useadds an object element at the end of the array{loader: require.resolve('less-loader')}.


After the modification is complete:


// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
  test: /\.(css|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
        // 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')
    }
  ],
},


At this point, the support for Create-react-app has been completed.


Effect validation


Finally, verify that the configuration is in effect in our experimental project.



Start by using the less syntax in thesrcroot directory to create a less file namedTest.less:


@title-color:#f00;.App-title {    color: @title-color  }


ThenApp.jsimport the less file in the file by using the following API:


import './Test.less';


yarn startrun our program again, and ifWelcome to Reactthe title turns red then there is no problem with the configuration.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.