React+Webpack4+Antd+Babel8搭建

声明:

本文大量参考了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.jswebpack.dev.conf.jswebpack.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文件夹看到编译好的网页,可以查看效果。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值