使用 Parcel 打包的 React HelloWorld 應用。GitHub 地址: https://github.com/justjavac/...html
mkdir react-helloworld cd react-helloworld
yarn init -y
或java
npm init -y
此時會建立要給 package.json 文件,文件內容:node
{ "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" }
yarn:react
yarn add react react-dom
npm:git
npm install react react-dom --save
package.json 文件內容:github
{ "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" + } }
新建 .babelrc 文件npm
touch .babelrc
輸入內容:json
{ "presets": ["react"] }
添加 babel-preset-react:瀏覽器
yarn:babel
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" + } }
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" } }
內容
<html> <body> <div id="root"></div> <script src="./index.js"></script> </body> </html>
import React from "react"; import ReactDOM from "react-dom"; const App = () => { return <h1>Hello World!</h1>; }; ReactDOM.render(<App />, document.getElementById("root"));
{ "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" } }
運行
yarn start
或
npm start
在瀏覽器中打開 http://localhost:1234
打包過程會生產 .cache 和 dist 兩個目錄,若是是 git 工程,能夠新建 .gitignore 文件忽略這兩個目錄:
.cache dist node_modules
GitHub 地址: https://github.com/justjavac/...