声明:
本文大量参考了Presbyterian的文章webpack4+react+antd从零搭建React脚手架(一)和webpack4+react+antd从零搭建React脚手架(二),并结合了自己的实际操作,重构了搭建流程,修改了部分描述错误,并具体化了某些配置步骤。
0. 安装Node.js
安装好后再在命令行输入命令:
node --version
能看到版本号就ok了
1. 项目初始化
首先在命令行切到新建项目的目录,执行
npm init
此时会要求输入项目描述,版本号,作者,项目地址等等,配置完成后生成package.json
文件。
2. 安装webpack
安装:
npm install --save-dev webpack webpack-cli
--save-dev
是将依赖安装到开发环境中,即在package.json
中的devDependencies
目录下。--save
是安装到生产环境中也就是在package.json
中的dependencies
目录下。
2.1 安装模块
-
webpack-merge 因为分成3个配置文件所以需要进行合并,当然也可以不使用同一放到一个配置里。
npm install --save-dev webpack-merge
-
HtmlWebpackPlugin 用于自动产生html文件。
npm install --save-dev html-webpack-plugin
-
clean-webpack-plugin 用于在build过程中,清理dist文件夹
npm install --save-dev clean-webpack-plugin
-
webpack-dev-server 热加载模块
npm install --save-dev webpack-dev-server
2.2 配置
2.2.1 配置config
在根目录下建立build
文件夹,分别新建三个名为的webpack.base.conf.js
、webpack.dev.conf.js
、webpack.prod.conf.js
的配置文件。分别是公共配置,开发配置,生产配置。
mkdir build
type nul> build\webpack.base.conf.js
type nul> build\webpack.dev.conf.js
type nul> build\webpack.prod.conf.js
在webpack.base.conf.js
写下配置:
const path = require('path'); //node.js自带的路径参数
const APP_PATH = path.resolve(__dirname, '../src'); //源文件目录
const DIST_PATH = path.resolve(__dirname, '../dist'); //生产目录
module.exports = {
entry: {
app: './src/index.js',
},
output: {
filename: 'js/[name].[hash].js', //使用hash进行标记
path: DIST_PATH
},
};
在webpack.dev.conf.js
写下配置:
const path = require('path');
const merge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.base.conf.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = merge(baseWebpackConfig, {
mode: 'development',
output: {
filename: "js/[name].[hash:16].js",
},
devtool: 'inline-source-map', // 源错误检查
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
inject: 'body',
minify: {
html5: true
},
hash: false
}),
new webpack.HotModuleReplacementPlugin(), // 热更新
],
devServer: { // 热更新服务配置
port: '3000',
contentBase: path.join(__dirname, '../public'),
compress: true,
historyApiFallback: true,
hot: true, //开启
https: false,
noInfo: true,
open: true,
proxy: {}
}
});
在webpack.prod.conf.js
写下配置:
const merge = require('webpack-merge'); //合并配置
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = merge(baseWebpackConfig, {
mode: 'production', //mode是webpack4新增的模式
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.html',
title: 'PresByter', //更改HTML的title的内容
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
}),
]
});
添加网页文件
在根目录下创建src
目录,然后创建index.js
文件:
mkdir src
type nul> src\index.js
在src\index.js
中写下配置:
import React from "react";
import ReactDom from "react-dom";
const Div = document.createElement("div");
Div.setAttribute("id", "root")
document.body.appendChild(Div)
ReactDom.render(
<div>
<h1>hello, world!</h1>
</div>,
document.getElementById("root")
);
在根目录创建一个public
文件夹,然后新建一个index.html
文件:
mkdir public
type nul> public\index.html
在public\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>
<%= htmlWebpackPlugin.options.title %>
</title>
</head>
<body>
</body>
</html>
添加命令
在package.json
文件scripts
属性添加build
命令和dev
命令:
{
......
"scripts": {
"build": "webpack --config build/webpack.prod.conf.js",
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
......
}
安装React
安装:
npm install --save react react-dom
安装Babel
安装Babel:
npm install --save-dev babel-loader babel-plugin-import
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react
npm install --save-dev @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties
npm install --save @babel/runtime
配置Babel
在根目录下创建.babelrc
文件:
type nul> .babelrc
配置.babelrc
:
{
"presets": ["@babel/preset-react", "@babel/preset-env"],
"plugins": [
["@babel/plugin-proposal-class-properties"]
]
}
在build\webpack.base.conf.js
添加babel相关配置:
const path = require('path'); //node.js自带的路径参数
const APP_PATH = path.resolve(__dirname, '../src'); //源文件目录
const DIST_PATH = path.resolve(__dirname, '../dist'); //生产目录
module.exports = {
entry: {
app: './src/index.js',
},
output: {
filename: 'js/[name].[hash].js', //使用hash进行标记
path: DIST_PATH
},
module: {
rules: [
{
test: /\.js?$/,
use: "babel-loader",
include: APP_PATH
}
]
}
};
运行
至此webpack+react搭建完成
build
构建:
npm run build
dev
开发模式实时更新:
npm run dev
构建完成后可在dist\index.html
文件夹看到编译好的网页,可以查看效果。
安装antd
安装样式表插件
npm install --save-dev file-loader url-loader
npm install --save-dev style-loader css-loader postcss-loader autoprefixer
npm install --save-dev less sass less-loader node-sass
在webpack.base.conf.js
添加配置:
{
......
rules: [
{
test: /\.js?$/,
use: "babel-loader",
include: APP_PATH
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader',],
},
{
test:/\.less$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{
loader: "postcss-loader",//自动加前缀
options: {
plugins: [
require('autoprefixer')({browsers:['last 5 version']})
]
}
},
{ loader: "less-loader" }
]
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader", },
{ loader: "sass-loader" },
{ loader: "postcss-loader",
options: {
plugins: [
require('autoprefixer')({browsers: ['last 5 version']})
]
}
}
]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
name: "images/[name].[ext]",
limit: 1000 //是把小于1000B的文件打成Base64的格式,写入JS
}
}]
},
{
test: /\.(woff|svg|eot|woff2|tff)$/,
use: 'url-loader',
exclude: /node_modules/ // exclude忽略/node_modules/的文件夹
},
]
......
}
安装antd
npm install antd
修改.babelrc
配置:
{
"presets": ["@babel/preset-react", "@babel/preset-env"],
"plugins": [
["@babel/plugin-proposal-class-properties"],
["import", {"libraryName": "antd", "style": "css"}]
]
}
创建src\images
文件夹和index.css
文件,并在src\images
文件夹下放一张名为test.png
的图片:
mkdir src\images
type nul> src\index.css
修改src\index.js
引入antd
组件:
import React from "react";
import ReactDom from "react-dom";
import { Button, Switch } from 'antd';
import 'antd/dist/antd.css';
import styles from './index.css'
import Pic from './images/test.png'
const Div = document.createElement("div");
Div.setAttribute("id", "root")
document.body.appendChild(Div)
ReactDom.render(
<div>
<h1>hello, world!</h1>
<Button type="primary">Primary</Button>
<Switch defaultChecked />
<br />
<img src={Pic}></img>
</div>,
document.getElementById("root")
);
修改src\index.css
:
body {
background-color: #333333;
}
h1 {
color: #FFFFFF;
}
运行
至此webpack+react+antd搭建完成
build
构建:
npm run build
构建完成后可在dist\index.html
文件夹看到编译好的网页,可以查看效果。