使用 Parcel 打包的 React HelloWorld 應用。GitHub 地址: github.com/justjavac/p…
0. 新建目錄
mkdir react-helloworld
cd 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 檔案
內容
<html>
<body>
<div id="root"></div>
<script src="./index.js"></script>
</body>
</html>
複製程式碼
7. 新建 index.js 檔案
import React from "react";
import ReactDOM from "react-dom";
const App = () => {
return <h1>Hello World!</h1>;
};
ReactDOM.render(<App />, 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
複製程式碼
在瀏覽器中開啟 http://localhost:1234
打包過程會生產 .cache 和 dist 兩個目錄,如果是 git 工程,可以新建 .gitignore 檔案忽略這兩個目錄:
.cache
dist
node_modules
複製程式碼
GitHub 地址: github.com/justjavac/p…