手动搭建 ReactJS 项目
创建项目
mkdir react-app
cd react-app
npm init
安装 Webpack 包
npm install --save-dev webpack
配置 webpack.config.js
var path = require('path');
module.exports = {
entry: ['./app/index.js'],
devServer: {
contentBase: './',
host: 'localhost',
compress: true,
port: 1717
},
module:{
rules:[
{
test:/\.js$/,
exclude:/node_modules/,
loader:"babel-loader",
query:{
presets:['@babel/env','@babel/react']
}
}
]
},
output: {
filename: 'index.js',
path: path.resolve(__dirname,'dist'),
publicPath: 'temp/'
}
}
新建 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>React全家桶-jspang</title>
</head>
<body>
<div id="app"></div>
</body>
<script src="./dist/index.js"></script>
</html>
开发服务器配置
npm install --save-dev webpack-dev-server
修改 webpack.config.js(参照末尾完整webpack.config.js)
修改 package.json
"scripts": {
"build": "webpack",
"server": "webpack-dev-server --open"
},
自动刷新浏览器
Babel 安装配置
npm install --save-dev babel-core babel-loader babel-preset-env(babel-preset-es2015) babel-preset-react
配置 model(参照末尾完整webpack.config.js)
安装 React
npm install --save react react-dom
编写 index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<div>Hello JSPang</div>,
document.getElementById("app")
);
完整 webpack.config.js
var path = require('path');
var extractTextWebpackPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: ['./app/index.js'],
devServer: {
contentBase: './',
host: 'localhost',
compress: true,
port: 1717
},
module:{
rules:[
{
test:/\.js$/,
exclude:/node_modules/,
loader:"babel-loader",
query:{
presets:['@babel/env','@babel/react']
}
},
{
test:/\.css$/,
use:extractTextWebpackPlugin.extract({
fallback:"style-loader",
use:[
"css-loader"
]
})
}
]
},
plugins:[
new extractTextWebpackPlugin("./index.css")
],
output: {
filename: 'index.js',
path: path.resolve(__dirname,'dist'),
publicPath: 'temp/'
}
}
完整package.json
{
"name": "webpack-app",
"version": "1.0.0",
"description": "webpack app",
"main": "./app/index.js",
"scripts": {
"build": "webpack",
"server": "webpack-dev-server --open"
},
"author": "xzg",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"@babel/preset-react": "^7.0.0",
"@babel/preset-stage-0": "^7.0.0",
"babel-loader": "^8.0.4",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-react-transform": "^3.0.0",
"css-loader": "^1.0.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"style-loader": "^0.23.1",
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
}
}