在之前的一篇博客中,使用了Webpack4来构建一个React+Redux开发环境(详情请看这里:https://blog.csdn.net/daydream13580130043/article/details/83480222),整个构建过程还是挺费劲的,所以在本篇博客中将使用令一种构建工具Parcel来重新构建React开发环境。
Parcel是啥,跟webpack,grunt,gulp一样是一个打包构建工具,不过它是零配置的,不需要配置任何东西,开箱即用,官方文档如下:https://parceljs.org/getting_started.html (整个文档都没几页,如果有webpack或其他构建工具的基础,几分钟就上手了)
言归正传,接下来我来使用Parcel构建React开发环境
首先使用yarn安装Parcel
yarn add parcel-bundler --dev
然后安装一些React的东西
yarn add react,react-dom
好了,我们的React开发环境搭建好了d=====( ̄▽ ̄*)b,Parcel直接支持动态导入,css文件导入,图片文件导入,模块热加载,代码拆分,ts文件等等,官网上都有。
然后我们在项目目录下,新建index.html,作为Parcel的入口,新建src文件夹,在src下新建index.js,show.js,show.css
在package.json加上
"scripts": {
"start": "node_modules/.bin/parcel index.html",
"build": "node_modules/.bin/parcel build index.html"
}
start是开发时用的,build是生产时用的
然后编辑index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="root">
</div>
</body>
<script src="./src/index.js"></script><!--js依赖-->
</html>
index.js
//动态导入Show组件
import React, {Component} from "react";
import ReactDOM from "react-dom";
const Other = props => <div style={
{
width: "100px",
height: "100px",
background: props.color,
color: "white",
textAlign: "center",
lineHeight: "100px"
}
}>{props.text}</div>;
class App extends Component {
constructor(props) {
super(props);
this.state = {
child: <Other text="click to load" color="coral"/>
};
}
handleClick() {
this.setState({
child: <Other text="loading" color="rebeccapurple"/>
});
//动态导入
import("./show").then(({Show}) => {
this.setState({
child: <Show/>
})
})
};
render() {
return (
<div onClick={this.handleClick.bind(this)}>
<button style={{border: "none", outline: "none", background: "deepskyblue"}}>click me</button>
{this.state.child}
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById("root"));
show.js
import React, {Component} from "react";
import "./show.css";
export class Show extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="show">
it is lazy load
</div>
)
}
}
show.css
.show {
width: 100px;
height: 100px;
background: blueviolet;
color: white;
text-align: center;
line-height: 100px;
}
上面的代码非常简单,没有什么难度
然后yarn run start 启动构建,默认运行在1234端口,是不是轻轻松松就构建了一个React开发环境,后期需要Redux,React-router,直接安装对应的包,建建文件夹,就Ok了。