从零开始搭建 creact-react-app 脚手架

Posted yang656

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从零开始搭建 creact-react-app 脚手架相关的知识,希望对你有一定的参考价值。

本次学习如何从零开始搭建一个react官方提供的脚手架并添加less配置项以及如何处理在搭建过程中出现的bug

在此过程中默认使用yarn工具,

使用官方提供的命令:(此过程可能会因为个人网速不同,创建的时间也会有所不一样)

>yarn create react-app sugar  

  技术图片

如图所示我们已经创建了一个基本的脚手架,但是由于在项目中我们会安装less插件,所以我们还需要将文件进行暴露,暴露文件的命令 yarn eject

>yarn eject
yarn run v1.17.3
$ react-scripts eject
NOTE: Create React App 2+ supports TypeScript, Sass, CSS Modules and more without ejecting: https://reactjs.org/blog/2018/10/01/create-react-app-v2.html

? Are you sure you want to eject? This action is permanent. (y/N)

  他会提示问你是否要暴露文件,这里可以直接回车,也可以选择y

到这一步,我们使用yarn start 启动项目试试看

>yarn start
yarn run v1.17.3
$ node scripts/start.js
? Something is already running on port 3000.

Would you like to run the app on another port instead? Yes
Starting the development server...
Failed to compile.

./src/index.js
Error: [BABEL] C:\\Users\\Sugar\\Desktop\\test\\sugar\\src\\index.js: Cannot find module ‘@babel/plugin-transform-react-jsx-source‘ (While processing: "C:\\\\Users\\\\Sugar\\\\Desktop\\\\test\\\\sugar\\\\node_modules\\\\babel-preset-react-app\\\\index.js$1")
    at Array.reduce (<anonymous>)

  此时你会发现他报错了!居然报错了,嗯  没错的,就是报错了,大概说的就是没找到哪个模块云云,百度找i到的解决方法有很多,其中我试过有效的有两种:

     1.去babel官方重新安装babel模块,但是这个方法我试过,不够粗暴。

  2.删掉node_module文件重新安装依赖。(此方法简单粗暴直接有效)。

 这里我选择删掉依赖模块重新安装,百试百灵,如果网速慢的话可以选择使用cnpm淘宝镜像安装。

>yarn start
yarn run v1.17.3
$ node scripts/start.js
? Something is already running on port 3000.

Would you like to run the app on another port instead? Yes
Starting the development server...
Compiled successfully!

You can now view sugar in the browser.

  Local:            http://localhost:3001/
  On Your Network:  http://192.168.0.101:3001/

Note that the development build is not optimized.
To create a production build, use yarn build.

  等待安装以来完成后就可以启动项目,你会发现项目成功启动

  接下来我们安装less

>yarn add less less-loader

  你以为这样就完成了吗?嗯  事情远远没有那么简单的,还需要在 config > webpack.config.js中进行一些配置项的修改。

找到   // style files regexes  windows的大概在文件四十行,然后添加

const lessRegex = /\\.less$/;
const lessModuleRegex = /\\.module\\.less$/;

  技术图片

  找到技术图片

  并复制,就在它下面粘贴

   修改为技术图片

  最后找到114行左右添加技术图片

 

 这样就完成了我们的less的配置,接下来就是在文件中使用,我在src下创建了一个文件夹技术图片

分别创建一个js和一个less,在js中引入技术图片

最后 我们可以看到在浏览器中我们的样式已经发生了改变,证明我们的less是生效了技术图片

最后就这样,如果对你有帮助,请给我点个赞

以上是关于从零开始搭建 creact-react-app 脚手架的主要内容,如果未能解决你的问题,请参考以下文章

P01: React Router 安装与环境搭建

从零开始搭建HTTPS服务

从零开始搭建系统4.2——概要设计

从零开始搭建系统4.1——需求分析

从零开始搭建系统4.3——详细设计

从零开始搭建系统3.5——日志组件开发