1. 程式人生 > >從零開始,使用Webpack4配置屬於自己的React專案

從零開始,使用Webpack4配置屬於自己的React專案

前言:預設意見安裝好Node和Npm,安裝命令用紅體字標出

1.專案工程配置

新建一個資料夾,然後在資料夾上開啟終端,輸入npm init -yes完成專案初始化,會生成一個package.json記錄整個專案的依賴包資訊。目錄結構如下

2.安裝Webpack和React並配置

安裝react npm i react react-dom redux react-redux redux-thunk react-router --save-dev

在目錄src下新建 index.tml.html 檔案(這個後面會講到使用webppac配置html模板):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>

在目錄src下新建 index.js 檔案:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <h1>這裡是一個簡單的示例頁面啊</h1>,
    document.getElementById('root')
);

安裝bable,用來解析js檔案loader及外掛去解析jsxes6語法:npm i babel-cli babel-loader babel-preset-env babel-preset-react babel-plugin-react-transform react-transform-hmr --save-dev

,在專案根目錄新建並配置.babelrc檔案:

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

安裝webpack npm i webpack webpack-cli webpack-dev-server --save-dev  ,在專案根目錄新建並配置webpack.config.js:

/*
 * @Author: qinghui_wu 
 * @Date: 2018-11-04 17:56:24 
 * @Last Modified by: qinghui_wu
 * @Last Modified time: 2018-11-10 16:07:04
 */

const path=require('path');
const ROOT_PATH = path.resolve(__dirname);

module.exports = {  
    entry: './src/index.js',//入口檔案
    output: {//輸出
        path: path.resolve(__dirname, 'dist'),
        filename: 'main.js'
    },
    devServer: {
        contentBase: require('path').join(__dirname, "dist"),//設定伺服器訪問的基本目錄
        compress: true,
        port: 8088,//埠
        host: "localhost",
        inline: true,//實時重新整理
    },
    module: {
        rules: [
             //這裡配置loader ,物件形式配置
        ]
    },
    plugins: [
        //這裡配置外掛
    ]
};

配置啟動命令,在package.json中的scripts中新增:

"dev": "webpack-dev-server --mode development --open",

這樣在資料夾終端就可以使用 npm run dev 啟動專案

配置解析.js和.jsx檔案的loader:

            {
                test: /\.(js|jsx)$/,
                exclude: path.resolve(__dirname, 'node_modules'),//忽略查詢
                include: path.resolve(__dirname, 'src'),//查詢
                use: {
                    loader: "babel-loader"
                }
            }

安裝配置webpack外掛html-webpack-plugin,npm i html-webpack-plugin --save-dev

const HtmlWebPackPlugin = require("html-webpack-plugin");//引用都放在const path=require('path');旁邊

        //這段放在plugins下
        new HtmlWebPackPlugin({
            template: ROOT_PATH + "/src/index.tmpl.html",//index html 模板
            filename: 'index.html',// 生成檔名
            minify: {
                collapseWhitespace: true, //把生成的 index.html 檔案的內容的沒用空格去掉,減少空間
            },
            hash: true, //為了更好的 cache,可以在檔名後加個 hash。
        }),

安裝配置分離js和css外掛、清理無效檔案外掛,npm i mini-css-extract-plugin clean-webpack-plugin --save-dev,(這裡用mini-css-extract-plugin替代ExtractTextPlugin)

const MiniCssExtractPlugin = require("mini-css-extract-plugin");//分離css和js 配置style loader使用
const CleanWebpackPlugin = require('clean-webpack-plugin');//清理無效檔案
        //這段放在plugins下
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: "[name].css",
            chunkFilename: "[id].css"
        }),
        new CleanWebpackPlugin(['dist'])//例項化,引數為目錄

安裝配置樣式檔案解析相關loader,這裡使用less和css,npm install less less-loader css-loader style-loader postcss-loader autoprefixer -D

           { 
                test: /\.(css|less)$/, //樣式loader
                use:[
                        MiniCssExtractPlugin.loader,
                        {   
                            loader:"css-loader",
                            options:{
                                modules: true, // 指定啟用css modules
                                localIdentName: '[name]__[local]--[hash:base64:5]' // 指定css的類名格式
                            }
                        },
                        "postcss-loader",//自動新增字首
                        "less-loader"
                ]
            }

配置postcss-loader自動新增字首(autoprefixer),在和webpack.config.js同級目錄新增postcss.config.js

module.exports = {
    plugins: {
        'autoprefixer': {
            browsers: ['iOS >= 7', 'Android >= 4.1',
                'last 10 Chrome versions', 'last 10 Firefox versions',
                'Safari >= 6', 'ie > 8']
        },
    }
}

安裝配置圖片、字型檔案的解析用的loader,npm i file-loader url-loader --save-dev

            {
                test: /\.(png|jpg|gif|woff|svg|eot|woff2|tff)$/,
                use: 'url-loader?limit=8129', //limit的引數,當你圖片大小小於這個限制的時候,會自動啟用base64編碼圖片
                exclude: /node_modules/
            }