React

yarn

Yarn 对你的代码来说是一个包管理器, 你可以通过它使用全世界开发者的代码,或者分享自己的代码。 Yarn 做这些快捷、安全、可靠,所以你不用担心什么。

全局安装 yarn

npm install -g yarn

安装

以官方为例:create-react-app

在桌面创建一个文件夹,我把它命名为create-react-app,然后用命令行输入:

1
2
3
4
5
6
7
npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start
//或者
yarn start
//(此处使用了yarn start)

至此,便为成功。


此时,回到create-react-app目录中,目录结构为:

  • src 目录,用于存放所有源代码,最重要的就是 index.js 了。跟起步webpack中的 src/index.js 是一个意思。
  • public 目录,用于存放静态资源(不需要 build 的资源),如 public/index.html
  • build 目录,运行 yarn run build 或者 npm run build 就可以看到 build 目录了

  • yarn.lock 文件,描述了我们安装的 node 包的所有版本

create-react-app 内置了 webpack 的所有功能,不需要我们配置,我们只需要运行 yarn run start 或者 yarn run build 就行了,其他的都不用我们操心。

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "hello-world",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-scripts": "1.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}

部署

根据运行yarn run build所得的提示:

运行以下代码后

1
2
git add .
git commit -m 'update'

再运行git suatus,发现没有显示任何文件变动,原因是.gitignore 被 create-react-app 改掉了,需要删除 .gitignore 里面的 /build 这一行。

然后按照提示,在 package.json 里添加

1
"homepage": "https://selfimper.github.io/react-todo/build"

接着运行:

1
2
3
4
yarn run build
git add .
git commit -m "build"
git push

就可以打开页面预览了。览页面网址类似于:https://selfimper.github.io/react-todo/build/index.html