webpack4+react 多页面打包

目录结构(先创建好)

简单说明一下 下面有代码的直接粘贴复制 有些没有代码的 这里先解释一下

1.node_modules 这个文件夹没什么好说的

2.src 这个文件夹里面就是我们需要写的

   (1).src/component 这里一般都是方组件的 我没有写组件 所以这里空空如也 

   (2).src/pages 这里放的就是打包的页面了 

   (3).src/pages 里面pageinfo.json 这个文件是配置单独页面的一些seo之类的配置 不写的 生成模板是会有默认的 代码很简单                  稍微看一下就明白

   (4).关于.scss文件 因为我现在就在用scss 所有这里就用scss 没有用 css上面的 有需要的可以自己配置下百度一下很简单

下面就是一些主要代码 希望能对在看此篇文章的你起到帮助作用

一、生成模板文件

//create-html.js

const fs = require("fs");
const HtmlWebpackPlugin = require("html-webpack-plugin"); //生成html文件
const getPath = require("./get-path");
let htmlArr = [];

function createHtml(page_path) {
    getPath(page_path).map((item) => {
        let infoJson = {},
            infoData = {};
        try {
            // 读取pageinfo.json文件内容,如果在页面目录下没有找到pageinfo.json 捕获异常
            infoJson = fs.readFileSync(`${page_path}/${item}/pageinfo.json`, "utf-8"); //
            infoData = JSON.parse(infoJson);
        } catch (err) {
            infoData = {};
        }
        htmlArr.push(new HtmlWebpackPlugin({
            title: infoData.title ? infoData.title : "多页面demo",
            meta: {
                keywords: infoData.keywords ? infoData.keywords : "多页面demo",
                description: infoData.description ? infoData.description : "多页面demo"
            },
            chunks: [`${item}/${item}`], //引入的js
            template: "./src/template.html",
            filename: item == "index" ? "index.html" : `${item}/index.html`, //html位置
            minify: { //压缩html
                collapseWhitespace: true,
                preserveLineBreaks: true
            },
        }));
    });
    return htmlArr;
}


module.exports = createHtml;

二、配置入口文件

//get-entry.js


const getPath = require("./get-path");
/**
 * 【获取entry文件入口】
 *
 * @param {String} path 引入根路径
 * @returns {Object} 返回的entry { "about/aoubt":"./src/about/about.js",...}
 */
module.exports = function getEnty(path) {
    let entry = {};
    getPath(path).map((item) => {
        /**
         * 下面输出格式为{"about/about":".src/aobout/index.js"}
         * 这样目的是为了将js打包到对应的文件夹下
         */
        entry[`${item}/${item}`] = `${path}/${item}/index.jsx`;
    });
    return entry;
};

三、遍历目录

//get-path.js

const fs = require("fs");

/**
 * 【遍历某文件下的文件目录】
 *
 * @param {String} path 路径
 * @returns {Array} ["about","index"]
 */
module.exports = function getPath(path) {
    let arr = [];
    let existpath = fs.existsSync(path); //是否存在目录
    if (existpath) {
        let readdirSync = fs.readdirSync(path); //获取目录下所有文件
        readdirSync.map((item) => {
            let currentPath = path + "/" + item;
            let isDirector = fs.statSync(currentPath).isDirectory(); //判断是不是一个文件夹
            if (isDirector) { // component目录下为组件 需要排除
                arr.push(item);
            }
        });
        return arr;
    }
};

四、webpack.config.js文件

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); //css分离打包
const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); //js压缩
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin"); //css压缩
const createHtml = require("./config/create-html"); // html配置
const getEntry = require("./config/get-entry");
const entry = getEntry("./src/pages");
const htmlArr = createHtml("./src/pages");

//主配置
module.exports = (env, argv) => ({
    entry: entry,
    output: {
        path: path.join(__dirname, "build"),
        filename: "[name].js"
    },
    module: {
        rules: [{
                test: /\.js[x]$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: [
                            "@babel/preset-env",
                            "@babel/preset-react",
                            { "plugins": ["@babel/plugin-proposal-class-properties"] } //这句很重要 不然箭头函数出错
                        ],
                    }
                },
            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"],
                exclude: /node_modules/,
            },
            {
                test: /\.(scss|css)$/, //css打包 路径在plugins里
                use: [
                    argv.mode == "development" ? { loader: "style-loader" } : MiniCssExtractPlugin.loader,
                    { loader: "css-loader", options: { url: false, sourceMap: true } },
                    { loader: "sass-loader", options: { sourceMap: true } }
                ],
                exclude: /node_modules/,
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]',
                options: {
                    publicPath: '/'
                }
            },

        ],
    },
    devServer: {
        // port: 3100,
        open: true,
    },
    resolve: {
        alias: {
            src: path.resolve(__dirname, "src/"),
            component: path.resolve(__dirname, "src/component/"),
            store: path.resolve(__dirname, "src/store/"),
        }
    },
    plugins: [
        ...htmlArr, // html插件数组
        new MiniCssExtractPlugin({ //分离css插件
            filename: "[name].css",
            chunkFilename: "[id].css"
        })
    ],
    optimization: {
        minimizer: [ //压缩js
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: false
            }),
            new OptimizeCSSAssetsPlugin({})
        ],
        splitChunks: { //压缩css
            cacheGroups: {
                styles: {
                    name: "styles",
                    test: /\.css$/,
                    chunks: "all",
                    enforce: true
                }
            }
        }
    }
});

五、package.json文件

{
    "name": "demo",
    "version": "1.3.0",
    "description": "demo",
    "main": "index.js",
    "scripts": {
        "start": "webpack-dev-server  --mode development --devtool inline-source-map --hot",
        "build": "webpack --mode production"
    },
    "author": "leinov",
    "license": "MIT",
    "devDependencies": {
        "@babel/core": "^7.1.2",
        "@babel/plugin-proposal-class-properties": "^7.2.1",
        "@babel/preset-env": "^7.1.0",
        "@babel/preset-react": "^7.0.0",
        "babel-loader": "^8.0.4",
        "babel-preset-react": "^6.24.1",
        "clean-webpack-plugin": "^0.1.19",
        "cross-env": "^5.2.0",
        "css-loader": "^1.0.0",
        "extract-text-webpack-plugin": "^4.0.0-alpha.0",
        "file-loader": "^2.0.0",
        "html-webpack-plugin": "^3.2.0",
        "mini-css-extract-plugin": "^0.4.3",
        "node-sass": "^4.9.3",
        "optimize-css-assets-webpack-plugin": "^5.0.1",
        "postcss-loader": "^3.0.0",
        "sass-loader": "^7.1.0",
        "style-loader": "^0.23.0",
        "uglifyjs-webpack-plugin": "^2.0.1",
        "url-loader": "^1.1.1",
        "webpack": "^4.20.2",
        "webpack-cli": "^3.1.2",
        "webpack-dev-server": "^3.1.9"
    },
    "dependencies": {
        "bulma": "^0.7.1",
        "express": "^4.16.3",
        "opn": "^5.4.0",
        "react": "^16.5.2",
        "react-dom": "^16.5.2",
        "react-redux": "^6.0.0",
        "redux": "^4.0.1"
    }
}

六、模板的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="Content-type" content="text/html; charset=utf-8" />
    <title>
        <%= htmlWebpackPlugin.options.title %>
    </title>
</head>

<body>
    <div id="root"></div>
</body>

</html>

 七、页面内容(因为我也是个小白 所以写的很烂 不要介意啊 )

// pages/index/index.jsx

import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
    render() {
        return (
            <div>
                <a href="../about/index.html">打开相关页面</a>
            </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById("root"));

// pages/about/index.jsx

import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
    render() {
        return (
            <div>
                <a href="/index.html">返回首页</a>
            </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById("root"));

总结 大部分代码就是这个样子 不想粘贴复制的的话 可以直接下载上面的资源 尝试着跑一下 

资源:https://download.csdn.net/download/divpoxiao/12710227

npm install  安装依赖文件

npn run build 打包

npm run dev 本地运行 及热更新 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

招来红月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值