基本构建(React, webpack, and Babel 7)
项目初始化
1 | mkdir react-project && cd $_ |
配置 webpack
1 | npm i webpack --save-dev |
增加 package.json
脚本
1 | "scripts": { |
配置 Babel
babel-loader
is the Webpack loader responsible for taking in the ES6 code and making it understandable by the browser of choice.
1.babel preset env for compiling Javascript ES6 code down to ES5 (please note that babel-preset-es2015 is now deprecated).
2.babel preset react for compiling JSX and other stuff down to Javascript.
安装依赖:
1 | npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev |
创建 .babelrc
文件:
1 | { |
到此我们可以开始配置一个最简单的 webpack.config.js
文件:
1 | module.exports = { |
创建两个示例组件
安装:
1 | npm i react react-dom |
创建目录结构:
1 | mkdir -p src/js/components/{container,presentational} |
创建一个简单的展示组件:
1 | touch src/js/components/container/FormContainer.jsx |
1 | import React, { Component } from "react"; |
创建另一个组件:
1 | touch src/js/components/presentational/Input.jsx |
1 | import React from "react"; |
最好使用 prop-types
确保类型准确:
1 | npm i prop-types --save-dev |
现在完善下前面的组件:
1 | import React, { Component } from "react"; |
组合
webpack 默认入口为 ./src/index.js
,创建该文件并引入组件:
1 | import FormContainer from "./js/components/container/FormContainer.jsx"; |
输出的文件在:
1 | ./dist/main.js |
增加 HTML webpack plugin
1 | npm i html-webpack-plugin html-loader --save-dev |
更新 webpack 配置:
1 | const HtmlWebPackPlugin = require("html-webpack-plugin"); |
创建一个HTML文件 ./src/index.html
:
1 |
|
将 react 组件渲染到 html
修改 ./src/js/components/container/FormContainer.jsx
,在底部添加:
1 | const wrapper = document.getElementById("create-article-form"); |
配置开发环境
安装 webpack-dev-server
1 | npm i webpack-dev-server --save-dev |
package.json
增加 dev 指令:
1 | "scripts": { |
添加 react-router
添加 redux
添加 redux-thunk
相关链接
A Complete React Boilerplate Tutorial — From Zero to Hero
How to build your own React boilerplate
Tutorial: How to set up React, webpack, and Babel 7 from scratch (2019)
Webpack 4 Tutorial: from 0 Conf to Production Mode