初始化一个react项目的过程
1、新建项目文件夹,npm init
文件夹结构:
2、安装react所需依赖,cnpm install –save react react-dom babelify babel-preset-react babel-preset-es2015
3、全局安装webpack(cnpm i -g webpack webpack-dev-server),当前项目安装(cnpm i webpack webpack-dev-server –save)
4、新建webpack.config.js文件,初始化webpack配置(注意实现热更新还要装html-webpack-plugin这个插件)
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: __dirname + '/src',
entry:"./js/index.js",
module:{
rules:[{
test:/\.js?$/,
exclude:/(node_modules)/,
loader:'babel-loader',
query:{
presets:['react','es2015']
}
}]
},
output:{
path:__dirname + '/src/',
filename:'bundle.js'
},
performance: {
hints:false
},
mode:'production',
plugins:[
new HtmlWebpackPlugin({
template: '../index.html'
}),
new webpack.HotModuleReplacementPlugin()
]
}
5、index.js
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello World</h1>,
document.getElementById('example')
)
6、index.html
<div id="example"></div>
<script src="./src/bundle.js"></script>
7、package.json(重点是scripts里面的dev中的命令,使用npm run dev就相当于使用其中的命令)
{
"name": "reactproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --content-base src --inline --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babelify": "^10.0.0",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"webpack": "^4.20.2",
"webpack-dev-server": "^3.1.9"
},
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack-cli": "^3.1.2"
}
}
最后使用npm run dev即可在默认8080端口上访问index.html