使用 打包的 React HelloWorld 应用。GitHub 地址:
0. 新建目录
mkdir react-helloworldcd react-helloworld复制代码
1. 初始化 npm
yarn init -y复制代码
或
npm init -y复制代码
此时会创建要给 package.json 文件,文件内容:
{ "name": "parcel-example-react-helloworld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}复制代码
2. 添加 React
yarn:
yarn add react react-dom复制代码
npm:
npm install react react-dom --save复制代码
package.json 文件内容:
{ "name": "parcel-example-react-helloworld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "",- "license": "ISC"+ "license": "ISC",+ "dependencies": { + "react": "^16.2.0",+ "react-dom": "^16.2.0"+ } }复制代码
3. 添加 Babel
新建 .babelrc 文件
touch .babelrc复制代码
输入内容:
{ "presets": ["react"]}复制代码
添加 babel-preset-react:
yarn:
yarn add babel-preset-react -D复制代码
npm:
npm install babel-preset-react --D复制代码
此时 package.json 文件内容:
{ "name": "parcel-example-react-helloworld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "react": "^16.2.0", "react-dom": "^16.2.0"- }+ },+ "devDependencies": { + "babel-preset-react": "^6.24.1"+ } }复制代码
5. 添加 Parcel
yarn:
yarn add parcel-bundler -D复制代码
npm:
npm install parcel-bundler --D复制代码
此时 package.json 文件内容:
{ "name": "parcel-example-react-helloworld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "react": "^16.2.0", "react-dom": "^16.2.0" }, "devDependencies": {- "babel-preset-react": "^6.24.1"+ "babel-preset-react": "^6.24.1",+ "parcel-bundler": "^1.0.3" } }复制代码
6. 新建 index.html 文件
内容
复制代码
7. 新建 index.js 文件
import React from "react";import ReactDOM from "react-dom";const App = () => { returnHello World!
;};ReactDOM.render(, document.getElementById("root"));复制代码
8. 添加打包命令
{ "name": "parcel-example-react-helloworld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {- "test": "echo \"Error: no test specified\" && exit 1"+ "start": "parcel index.html" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "react": "^16.2.0", "react-dom": "^16.2.0" }, "devDependencies": { "babel-preset-react": "^6.24.1" "babel-preset-react": "^6.24.1", "parcel-bundler": "^1.0.3" } }复制代码
9. 完成
运行
yarn start复制代码
或
npm start复制代码
在浏览器中打开
打包过程会生产 .cache 和 dist 两个目录,如果是 git 工程,可以新建 .gitignore 文件忽略这两个目录:
.cachedistnode_modules复制代码
GitHub 地址: