Jadual Kandungan
创建工程
目录结构
webpack 配置
webpack.base.conf.js(config -> webpack)
webpack.dev.conf.js
webpack.prod.conf.js
构建多界面
开发环境小技巧
Rumah hujung hadapan web tutorial js webpack4和react 搭建多页面应用的实现方法

webpack4和react 搭建多页面应用的实现方法

Aug 02, 2018 pm 02:28 PM
css html5 javascript

这篇文章给大家介绍的内容是关于webpack4和react 搭建多页面应用的实现方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

webpack 升级到4之后还没好好的同步一个可实用的webpack架子,接下来用webpack4来搭建一个简单的react的多界面应用,废话不说  直接撸码

创建工程

$ mkdir demo && cd demo
$ npm init -y
Salin selepas log masuk

目录结构

![工程目录结构][1]
Salin selepas log masuk

webpack 配置

安装react + babel 依赖

$ npm i -S react@16.3.0 react-dom@16.3.0

$ npm i -D webpack@4.4.1 webpack-cli@2.0.13 webpack-dev-server@3.1.1 webpack-merge@4.1.2 babel-cli@6.26.0 babel-preset-env@1.6.1 babel-preset-react@6.24.1 babel-preset-react-hmre@1.1.1 babel-loader@7.1.4 file-loader@1.1.11 url-loader@1.0.1
Salin selepas log masuk

webpack.base.conf.js(config -> webpack)

const entry = require("./webpack.entry.conf");
const newEntry = {};
for (let name in entry) {
    newEntry[name] = entry[name][0]
}
let config = {
    entry: newEntry,
    resolve: {
        extensions: [".js", ".json", ".jsx", ".css", ".pcss"],
    }
};
module.exports = config;
Salin selepas log masuk

webpack.dev.conf.js

const webpack = require('webpack');//引入webpack
const opn = require('opn');//打开浏览器
const merge = require('webpack-merge');//webpack配置文件合并
const path = require("path");
const baseWebpackConfig = require("./webpack.base.conf");//基础配置
const webpackFile = require("./webpack.file.conf");//一些路径配置
const eslintFormatter = require('react-dev-utils/eslintFormatter');

let config = merge(baseWebpackConfig, {
    /*设置开发环境*/
    mode: 'development',
    output: {
        path: path.resolve(webpackFile.devDirectory),
        filename: 'js/[name].js',
        chunkFilename: "js/[name].js",
        publicPath: ''
    },
    optimization: {
        runtimeChunk: {
            name: 'manifest'
        },
        // 包拆分
        splitChunks: {
            cacheGroups: {
                common: {   // 项目的公共组件
                    chunks: "initial",
                    name: "common",
                    minChunks: 2,
                    maxInitialRequests: 5,
                    minSize: 0
                },
                vendor: {   // 第三方组件
                    test: /node_modules/,
                    chunks: "initial",
                    name: "vendor",
                    priority: 10,
                    enforce: true
                }
            }
        }
    },
    plugins: [
        /*设置热更新*/
        new webpack.HotModuleReplacementPlugin(),
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: [
                    'babel-loader',
                    'cache-loader',
                ],
                include: [
                    path.resolve(__dirname, "../../app"),
                    path.resolve(__dirname, "../../entryBuild")
                ],
                exclude: [
                    path.resolve(__dirname, "../../node_modules")
                ],
            },
            {
                test: /\.(css|pcss)$/,
                loader: 'style-loader?sourceMap!css-loader?sourceMap!postcss-loader?sourceMap',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg|swf)$/,
                loader: 'file-loader?name=[name].[ext]&outputPath=' + webpackFile.resource + '/'
            },
            {
                test: /\.(js|jsx)$/,
                enforce: 'pre',
                use: [
                    {
                        options: {
                            formatter: eslintFormatter,
                            eslintPath: require.resolve('eslint'),
                            // @remove-on-eject-begin
                            baseConfig: {
                                extends: [require.resolve('eslint-config-react-app')],
                            },
                            //ignore: false,
                            useEslintrc: false,
                            // @remove-on-eject-end
                        },
                        loader: require.resolve('eslint-loader'),
                    },
                ],
                include: [
                    path.resolve(__dirname, "../../app")
                ],
                exclude: [
                    path.resolve(__dirname, "../../node_modules")
                ],
            }
        ]
    },
    /*设置api转发*/
    devServer: {
        host: '0.0.0.0',
        port: 8080,
        hot: true,
        inline: true,
        contentBase: path.resolve(webpackFile.devDirectory),
        historyApiFallback: true,
        disableHostCheck: true,
        proxy: [
            {
                context: ['/api/**', '/u/**'],
                target: 'http://10.8.200.69:8080/',
                secure: false
            }
        ],
        /*打开浏览器 并打开本项目网址*/
        after() {
            opn('http://localhost:' + this.port);
        }
    }
});
module.exports = config;
Salin selepas log masuk

webpack.prod.conf.js

const path = require('path');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const baseWebpackConfig = require("./webpack.base.conf");
const webpackFile = require('./webpack.file.conf');
const entry = require("./webpack.entry.conf");
const webpackCom = require("./webpack.com.conf");

let config = merge(baseWebpackConfig, {
    /*设置生产环境*/
    mode: 'production',
    output: {
        path: path.resolve(webpackFile.proDirectory),
        filename: 'js/[name].[chunkhash:8].js',
        chunkFilename: "js/[name]-[id].[chunkhash:8].js",
    },
    optimization: {
        //包清单
        runtimeChunk: {
            name: "manifest"
        },
        //拆分公共包
        splitChunks: {
            cacheGroups: {
                common: { //项目公共组件
                    chunks: "initial",
                    name: "common",
                    minChunks: 2,
                    maxInitialRequests: 5,
                    minSize: 0
                },
                vendor: {   //第三方组件
                    test: /node_modules/,
                    chunks: "initial",
                    name: "vendor",
                    priority: 10,
                    enforce: true
                }
            }
        }
    },
    plugins: [
        // extract css into its own file
        new ExtractTextPlugin('css/[name].[md5:contenthash:hex:8].css'),
        // Compress extracted CSS. We are using this plugin so that possible
        // duplicated CSS from different components can be deduped.
        new OptimizeCSSPlugin({
            assetNameRegExp: /\.css$/g,
            cssProcessor: require('cssnano'),
            cssProcessorOptions: {
                discardComments: {removeAll: true},
                // 避免 cssnano 重新计算 z-index
                safe: true
            },
            canPrint: true
        }),
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: [
                    'babel-loader',
                ],
            },
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.(css|pcss)$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader!postcss-loader"
                })
            },
            {
                test: /\.(png|jpg|gif|ttf|eot|woff|woff2|svg)$/,
                loader: 'url-loader?limit=8192&name=[name].[hash:8].[ext]&publicPath=' + webpackFile.resourcePrefix + '&outputPath=' + webpackFile.resource + '/'
            },
            {
                test: /\.swf$/,
                loader: 'file?name=js/[name].[ext]'
            }
        ]
    }
});
let pages = entry;
for (let chunkName in pages) {
    let conf = {
        filename: chunkName + '.html',
        template: 'index.html',
        inject: true,
        title: webpackCom.titleFun(chunkName,pages[chunkName][1]),
        minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true
        },
        chunks: ['manifest', 'vendor', 'common', chunkName],
        hash: false,
        chunksSortMode: 'dependency'
    };
    config.plugins.push(new HtmlWebpackPlugin(conf));
}
/* 清除 dist */
config.plugins.push(new CleanWebpackPlugin([webpackFile.proDirectory], {root: path.resolve(__dirname, '../../'), verbose: true, dry: false}));


/* 拷贝静态资源  */
copyArr.map(function (data) {
    return config.plugins.push(data)
});


module.exports = config;
Salin selepas log masuk

构建多界面

整体架构搭建起来之后
app -> component 

$ mkdir demo && cd demo

$ touch Index.jsx

    import React from 'react';

    class Index extends React.Component {
        render() {
            return (
                <p className="demo">
                    写个demo
                </p>
            );
        }
    }
    
    export default Index;
Salin selepas log masuk

在config -> entry

module.exports = [
    {
        name: 'index',
        path: 'index/Index.jsx',
        title: '首页',
        keywords: '首页',
        description: '首页'
    },
    {
        name: 'demo',
        path: 'demo/Index.jsx',
        title: 'demo',
        keywords: 'demo',
        description: 'demo'
    },
    {
        name: 'demo1',
        path: 'demo1/Index.jsx',
        title: 'demo1',
        keywords: 'demo1',
        description: 'demo1'
    }
];
Salin selepas log masuk

然后直接执行 npm run create-dev 就会在devBuild 和 entryBuild 中添加一个新的demo.html 和 demo.js

package.json

{
  "name": "webpack_es6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --devtool eval --progress --colors --profile --config config/webpack/webpack.dev.conf.js",
    "entry": "node config/entry/entryBuild.js",
    "devBuildHtml": "node config/webpack/webpack.devBuildHtml.conf.js",
    "create-dev": "npm run entry && npm run devBuildHtml",
    "build": "BABEL_ENV=production && webpack --progress --colors --config config/webpack/webpack.prod.conf.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.3.0",
    "react-dom": "^16.3.0"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-eslint": "^8.2.2",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-hmre": "^1.1.1",
    "cache-loader": "^1.2.2",
    "clean-webpack-plugin": "^0.1.19",
    "copy-webpack-plugin": "^4.5.1",
    "css-loader": "^0.28.11",
    "eslint": "^4.19.1",
    "eslint-config-react-app": "^2.1.0",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-flowtype": "^2.46.1",
    "eslint-plugin-import": "^2.10.0",
    "eslint-plugin-jsx-a11y": "^5.1.1",
    "eslint-plugin-react": "^7.7.0",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file": "^0.2.2",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.1.0",
    "optimize-css-assets-webpack-plugin": "^4.0.0",
    "postcss-cssnext": "^3.1.0",
    "postcss-loader": "^2.1.3",
    "precss": "^3.1.2",
    "react-dev-utils": "^5.0.0",
    "style-loader": "^0.20.3",
    "url-loader": "^1.0.1",
    "webpack": "^4.4.1",
    "webpack-cli": "^2.0.13",
    "webpack-dev-server": "^3.1.1",
    "webpack-merge": "^4.1.2"
  },
  "eslintConfig": {
    "extends": "react-app",
    "rules": {
      "import/no-webpack-loader-syntax": 0,
      "no-script-url": 0,
      "jsx-a11y/href-no-hash": 2
    }
  }
}
Salin selepas log masuk

开发环境小技巧

在开发环境添加cache-loader 可以提升在开发环境的编译速度

相关文章推荐:

react antd-mobile项目中如何实现 css 与 less 局部作用域化的功能

使用FormData()将ajax文件上传的代码

Atas ialah kandungan terperinci webpack4和react 搭建多页面应用的实现方法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

Video Face Swap

Video Face Swap

Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Alat panas

Notepad++7.3.1

Notepad++7.3.1

Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina

SublimeText3 versi Cina

Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Cara menggunakan bootstrap di vue Cara menggunakan bootstrap di vue Apr 07, 2025 pm 11:33 PM

Menggunakan bootstrap dalam vue.js dibahagikan kepada lima langkah: Pasang bootstrap. Import bootstrap di main.js. Gunakan komponen bootstrap secara langsung dalam templat. Pilihan: Gaya tersuai. Pilihan: Gunakan pemalam.

Peranan HTML, CSS, dan JavaScript: Tanggungjawab Teras Peranan HTML, CSS, dan JavaScript: Tanggungjawab Teras Apr 08, 2025 pm 07:05 PM

HTML mentakrifkan struktur web, CSS bertanggungjawab untuk gaya dan susun atur, dan JavaScript memberikan interaksi dinamik. Ketiga melaksanakan tugas mereka dalam pembangunan web dan bersama -sama membina laman web yang berwarna -warni.

Cara Menulis Garis Pecah Di Bootstrap Cara Menulis Garis Pecah Di Bootstrap Apr 07, 2025 pm 03:12 PM

Terdapat dua cara untuk membuat garis perpecahan bootstrap: menggunakan tag, yang mewujudkan garis perpecahan mendatar. Gunakan harta sempadan CSS untuk membuat garis perpecahan gaya tersuai.

Memahami HTML, CSS, dan JavaScript: Panduan Pemula Memahami HTML, CSS, dan JavaScript: Panduan Pemula Apr 12, 2025 am 12:02 AM

WebDevelopmentReliesOnhtml, CSS, andjavascript: 1) HtmlStructuresContent, 2) CSSStylesit, dan3) JavaScriptaddsInteractivity, Formingthebasisofmodernwebexperiences.

Cara memasukkan gambar di bootstrap Cara memasukkan gambar di bootstrap Apr 07, 2025 pm 03:30 PM

Terdapat beberapa cara untuk memasukkan imej dalam bootstrap: masukkan imej secara langsung, menggunakan tag HTML IMG. Dengan komponen imej bootstrap, anda boleh memberikan imej yang responsif dan lebih banyak gaya. Tetapkan saiz imej, gunakan kelas IMG-cecair untuk membuat imej boleh disesuaikan. Tetapkan sempadan, menggunakan kelas IMG-Sempadan. Tetapkan sudut bulat dan gunakan kelas IMG-bulat. Tetapkan bayangan, gunakan kelas bayangan. Saiz semula dan letakkan imej, menggunakan gaya CSS. Menggunakan imej latar belakang, gunakan harta CSS imej latar belakang.

Apa yang dirujuk oleh H5? Meneroka konteks Apa yang dirujuk oleh H5? Meneroka konteks Apr 12, 2025 am 12:03 AM

H5referstohtml5, apivotaltechnologyinwebdevelopment.1) html5introducesnewelementsandapisforrich, dynamicwebapplications.2) itsupp ortsmultimediawithoutplugins, enhancusexperienceaceacrossdevices.3) SemantikelementsImproveContentstructureandseo.4) H5'srespo

Cara Menyiapkan Kerangka untuk Bootstrap Cara Menyiapkan Kerangka untuk Bootstrap Apr 07, 2025 pm 03:27 PM

Untuk menubuhkan rangka kerja bootstrap, anda perlu mengikuti langkah -langkah ini: 1. Rujuk fail bootstrap melalui CDN; 2. Muat turun dan tuan rumah fail pada pelayan anda sendiri; 3. Sertakan fail bootstrap di HTML; 4. Menyusun sass/kurang seperti yang diperlukan; 5. Import fail tersuai (pilihan). Setelah persediaan selesai, anda boleh menggunakan sistem grid Bootstrap, komponen, dan gaya untuk membuat laman web dan aplikasi yang responsif.

Cara menggunakan butang bootstrap Cara menggunakan butang bootstrap Apr 07, 2025 pm 03:09 PM

Bagaimana cara menggunakan butang bootstrap? Perkenalkan CSS bootstrap untuk membuat elemen butang dan tambahkan kelas butang bootstrap untuk menambah teks butang

See all articles