从零开始构建 React + webpack4 项目

从零开始构建 React + webpack4 项目

1.npm的初始化

windows下 home + r 打开cmd

cd react_demo
npm init -y 
//or
npm init

2.下载依赖包

cnpm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin clean-webpack-plugin react react-dom babel-core@6 babel-loader@7 babel-preset-env babel-preset-es2015 babel-preset-react@6 css-loader style-loader less less-loader url-loader file-loader mini-css-extract-plugin

3.配置.babelrc

在根目录下新建.babelrc文件

{
    "presets":[
        "env",
        "react"
    ],
    "plugins": []
}

4.配置webpack

在根目录下新建webpack.config.js

const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const devMode = process.env.NODE_ENV !== 'production'
const extractLoader = devMode ? 'style-loader' : MiniCssExtractPlugin.loader

const webpackConfig = {
    entry: {
        index: './src/index.js'
    },
    output: {
        filename: '[name].[hash].bundle.js', //chunkhush 只用于生产环境,
        library: 'myLibrary',
        chunkFilename: '[name].[hash].chunk.js',
        path: path.resolve(__dirname, 'dist')
    },
    optimization: {
        // runtimeChunk: 'single',
        splitChunks: {
            cacheGroups: {
                commons: {
                    chunks: "initial",
                    minChunks: 2,
                    maxInitialRequests: 5,  // The default limit is too small to showcase the effect
                    minSize: 0              // This is example is too small to create commons chunks
                },
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    chunks: "initial",
                    name: "vendors",
                    priority: 10,
                    enforce: true,
                    chunks: 'all'
                }
            }
        }
    },
    devServer: {
        contentBase: 'dist',
        stats: {
            errors: true,               //echo errors 
            warnings: false,            //not echo warnings
            modules: false,             //not echo modules info
            reasons: true,              //reason of import module
            performance: true,
            children: false
        },
        hot: true,
        port: 9999
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: ["babel-loader"],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [extractLoader, 'css-loader'],
                exclude: /node_modules/
            },
            {
                test: /\.less$/,
                use: [extractLoader, 'css-loader', {
                    loader: 'less-loader',
                    options: { javascriptEnabled: true}
                }]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: ['file-loader']
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    'file-loader'
                ]
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        }),
        new CleanWebpackPlugin(
            [path.resolve(__dirname, 'dist')],
            {
                root: path.resolve(__dirname, '/'),     //配置根路径信息 to prevent the error: dist is outside of project root 
                exclude: [],
                verbose: true,                          //开启在控制台输出信息
                dry: false                              //启用删除文件
            }
        ),
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: devMode ? '[name].css' : '[name].[hash].css',
            chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
        }),
        new HtmlWebpackPlugin({
            template: `${__dirname}/src/index.html`,
            filename: 'index.html',
            title: 'webpack react',
            inject: 'body',
            meta: { viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no' }
        }),
    ]
}

module.exports = webpackConfig

5.配置npm脚本

package.json 中添加脚本命令

"scripts": {
    "dev": "webpack-dev-server --hot"
}

6.配置入口文件

结构目录如下

根目录
---
  |
  -- src
      |
      -- index.html
      -- index.js
      -- index.less
  |
  -- node_modules
  |
  -- .babelrc
  |
  -- .webpack.config.js
  |
  -- package.json
  |
  -- ReadMe.md

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>Document</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

index.js 内容

import React from 'react'
import ReactDOM from 'react-dom'
import './index.less'

class App extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <div>
        <h2>React 模板</h2>
        <h2><span style={{color: '#FF6347'}}>{ this.props.message }</span></h2>
      </div>
    )
  }
}

ReactDOM.render(<App message="I Love China"/>, document.getElementById('app'));

index.less 内容

html,body,h1,h2,h3,h4,h5,p,ul,li,ol {padding: 0; margin: 0;}

7.运行react项目

运行以下命令,并在浏览器中访问localhost:9999

npm run dev

8.集成AntD

推荐 babel-plugin-import 来按需引入

cnpm i -S babel-plugin-import

安装antd依赖包

cnpm i -S antd

.bablerc 文件中新增配置

"plugins": [
    ["import", {
        "libraryName": "antd",
        "libraryDirectory": "es",
        "style": true,      // `style: true` 会加载 less 文件
        // "style": "css" 
    }]
]

index.js中引入DatePicker, 然后直接使用组件

//引入DatePicker
import { DatePicker } from 'antd'

//使用 DatePicker
  render() {
    return (
      <div>
        <h2>React 模板</h2>
        <h2><span style={{color: '#FF6347'}}>{ this.props.message }</span></h2>
        <DatePicker></DatePicker>
      </div>
    )
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值