0x000 概述
开坑 react
系列文章,不知道会写到什么程度,毕竟写文章并不在行,存在当做笔记做,先不讲理论,实践先行。
0x001 初始化项目格式
$ mkdir react-study
$ cd react-study
$ mkdir 0x001-helloworld
$ git init
此时的目录结构:
+ react-study
- .gitignore
0x002 创建一个项目并配置 webpack
-
创建项目
$ mkdir 0x001-helloworld $ cd 0x001-helloworld $ npm init -y
-
添加依赖
// package.json { "name": "helloworld", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --color --process --hot" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "babel-cli": "^6.26.0", "babel-core": "^6.26.3", "babel-loader": "^7.1.5", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1", "html-webpack-plugin": "^3.2.0", "lerna": "^3.1.1", "webpack": "^4.16.5", "webpack-cli": "^3.1.0", "webpack-dev-server": "^3.1.5" }, "dependencies": { "react": "^16.4.2", "react-dom": "^16.4.2", "react-hot-loader": "^4.3.4" } }
-
安装依赖
$ npm install
-
添加
babel
对es6
和jsx
的支持// .babelrc { "presets": [ "env" ], "plugins": [ "transform-react-jsx" ] }
-
编写
webpack.config.js
const path = require('path') var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: path.resolve(__dirname, 'src/index.js'), mode: 'development', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js' }, devServer: { open: true }, module: { rules: [{ test: /\.js$/, loader: "babel-loader" }] }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, "src/index.html") }) ] }
-
编写源代码
-
创建目录
$ mkdir src
-
编写
html
// index.html <!doctype html> <html> <head> <title>React Study</title> </head> <body> <div id="app"></div> </body> </html>
-
编写
js
//index.js import React from 'react' import ReactDom from 'react-dom' ReactDom.render( <h1>Hello, world!</h1>, document.getElementById('app') );
-
- 此时完整目录结构
+ react-study
+ 0x001-helloworld
+ src
- index.html
- index.js
- .babelrc
- package.json
- webpack.config.js
0x003 运行项目
npm start
查看浏览器:http://localhost:8080/
成功!!!