使用create-react-app创建的React应用开发环境给了我们便利的同时也给我们很大的限制,最好的方式还是按照自己意愿去组合构建开发环境,形成一套适合自己或自己团队的可定制环境。
在开始环境搭建之前得安装Node,Git等基础软件工具。创建工程目录,并用npm init -y
初始化package.json文件。
mkdir learn-react
cd learn-react
npm init -y
安装webpack,webpack-dev-server,babel-core,babel-loader,babel-preset-env,babel-preset-react,html-webpack-plugin,clean-webpack-plugin等工具包和react, react-dom, prop-types等项目依赖包。编写打包配置文件webpack.config.js,并在package.json中增加运行命令。
注意:其中webpack,babel-core,babel-preset,babel-preset-react,babel-loader是必须的,其他的可选。
npm install --save-dev webpack webpack-dev-server babel-core babel-loader babel-preset-env babel-preset-react html-webpack-plugin clean-webpack-plugin
npm install --save react react-dom prop-types
打包配置文件webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); //html模板文件引用插件
const CleanWebpackPlugin = require('clean-webpack-plugin'); //删除目录插件
module.exports = {
resolve: {
extensions: ['.js','.jsx'] //解析文件类型
},
entry: './src/index.js', //打包入口
//模块解析规则
module: {
rules: [
{
test: /\.jsx?$/, // 解析文件类型
exclude: /node_modules/, //排除文件夹或文件
use: {
loader: "babel-loader", //解析插件
options: {
presets: ["env", "react"] //解析规则集,env对应babel-preset-env,主要用于JavaScript新特性适配,react对应babel-preset-react,主要用于jsx语法的解析
}
}
}
]
},
devtool: 'inline-source-map', // 报错代码追踪
devServer: {
contentBase: './dist' //服务启动基础目录
},
plugins: [
new CleanWebpackPlugin(['dist']), //删除dist目录
new HtmlWebpackPlugin({
title: 'Development', //页签名
template: 'template/index.html', // 模板文件
inject: 'body' // 生成文件自动插入方式
})
],
output: {
filename: "[name]-bundle.js", //生成文件名
path: path.resolve(__dirname, 'dist') //生成文件存放目录
}
};
项目依赖文件package.json
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack",
},
"keywords": [
"react"
],
"author": "Dreamer King",
"license": "MIT",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1",
"prop-types": "^15.5.10"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.16",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
}
}
其中,start命令以npm start
运行启动开发环境,而build命令是打包,以npm run build
运行。
到此,基础的开发环境配置完毕,可以编写代码啦!
附项目的目录结构如下: