项目 github 地址点击这里
1. npm 初始化
npm init
init
之后根据它的提示创建 package.json
,当然你也可以什么都不输入直接 enter
之后手动改 package.json
的内容也是可以的。

2. 添加 React,webpack
npm install react react-dom
npm install webpack webpack-dev-server webpack-cli -D
你也可以用下面的方式指定版本号下载
npm install react@16.3.1 react-dom@16.3.1
webpack
用于打包你写好的 js 代码,webpack-dev-server
可以起一个简单的本地开发服务器
3. 编写代码
- index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My React Project</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="dist/index.css" />
</head>
<body>
<div id="app"></div>
<script src="dist/index.js"></script>
</body>
</html>
- 页面结构js --- index.js
import React, { Component } from 'react';
import ReactDom from 'react-dom';
function HelloWorld() {
return <div>Hello World! </div>
}
ReactDom.render(<HelloWorld />, document.getElementById('app'));
- webpack 配置 webpack.config.js
const path = require('path');
module.exports = {
devtool: 'source-map', // 开启 sourceMap 方便调试
mode: 'development', // webpack 打包模式,build 的时候可以改为 production
devServer: { // webpack dev server 的一些配置参数,注意热更新如果在此处配置需要添加额外的插件,所以直接通过命令行的方式添加
host: '0.0.0.0',
port: '8000',
},
entry: './src/entry', // webpack 打包的入口文件,这里的路径就是上面写的 index.js 在项目里面的路径
output: { // webpack 打包的输出文件
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/'
},
module: { // 处理非标准 js 语法的 loader
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, 'src')
],
exclude: /node_modules/,
loader: 'babel-loader',
},
],
}
};
由于 React 写的是 jsx 语法,需要用 babel-loader
转码解析一下才能让
webpack 识别,所以需要下载相应的 babel 插件
npm install babel-core babel-loader babel-preset-env babel-preset-react -D
- .babelrc
{
"presets": ["env", "react"] // 对 ES6 和 React 语法进行解析
}
- package.json
{
"name": "react-project",
"version": "1.0.0",
"description": "a react project start from 0",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --color --hot",
"build": "webpack --mode=production",
"dev": "webpack --mode=development"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Unfantasy/react-project.git"
},
"author": "Unfantasy",
"license": "ISC",
"bugs": {
"url": "https://github.com/Unfantasy/react-project/issues"
},
"homepage": "https://github.com/Unfantasy/react-project#readme",
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.7"
}
}
这个时候执行 npm start
并用浏览器打开 http://localhost:8000
就可以看到 hello world 页面了。
下一篇:从零开始搭建 React项目(二)
网友评论