脚手架
Scaffolding is a meta-programming method of building database-backed software applications. It is a technique supported by some model-view-controller frameworks, in which the programmer may write a specification that describes how the application database may be used. The compiler uses this specification to generate code that the application can use to create, read, update and delete database entries, effectively treating the template as a “scaffold” on which to build a more powerful application.
from StackOverflow
所谓脚手架, 在我理解看来, 就是提供一个约定好的工具(框架). 按照约定来写自己的业务代码, 通过脚手架把约定的代码编译成真正能够执行的业务代码.
使用脚手架
react的脚手架其实非常多, 其中官方推荐的脚手架有下面这些:
- Create React App - An officially supported way to start a client-side React project with no configuration
- Next.js - Framework for server-rendered or statically-exported React apps
- Gatsby - Blazing-fast static site generator for React
- nwb - A toolkit for React apps, libraries and other npm modules for the web
- razzle - Create server-rendered universal JavaScript applications with no configuration
- Neutrino - Create and build modern JavaScript applications with zero initial configuration
我们选用create-react-app这个官方最为推荐的脚手架, 因为用这个相对来说更容易入门, 并且遇到问题都有解决方案.
安装脚手架环境
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
这样子一个react的项目就启动了. 整个项目的文件结构如下:
my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ └── favicon.ico
│ └── index.html
│ └── manifest.json
└── src
└── App.css
└── App.js //entry file
└── App.test.js
└── index.css
└── index.js
└── logo.svg
└── registerServiceWorker.js
启动react脚手架项目
npm start
yarn start
//二选一即可
build项目
一个项目start只是为了本地运行, 而想要生成打包好的文件, 就需要build了.
npm run build
yarn build
//二选一即可
这个时候打包出来的文件就会在build
目录下面, 会多出 index.html
和 static
目录. 其中static
目录下面的就是打包好的js, css
的文件. 可以直接引用.
遇到的疑问
为什么打包出来的文件名字有一串乱码.
ans : 这个是文件hash值, 为了防止浏览器缓存的. 想要更改, 看我下一篇博客.下载很慢怎么办
ans : npm在国内就是速度很慢, 请更改源地址为国内, 或者下载cnpm
.然后如何开发
ans : 下一篇博客, 讲如何在这个基础上, 自定义配置和开发.