webpack4配置,构建多页面应用(收藏)

package.json

     {
      "name": "dl-otc-es6",
      "version": "1.0.0",
      "description": "独龙OTC",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "webpack-dev-server --mode development --config ./build/webpack.dev.config.js",
        "build": "webpack --mode production --config ./build/webpack.prod.config.js"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "autoprefixer": "^9.3.1",
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "clean-webpack-plugin": "^0.1.19",
        "css-loader": "^1.0.1",
        "file-loader": "^2.0.0",
        "html-webpack-plugin": "^3.2.0",
        "image-webpack-loader": "^4.5.0",
        "less": "^3.8.1",
        "less-loader": "^4.1.0",
        "mini-css-extract-plugin": "^0.4.4",
        "optimize-css-assets-webpack-plugin": "^5.0.1",
        "postcss-loader": "^3.0.0",
        "style-loader": "^0.23.1",
        "uglifyjs-webpack-plugin": "^2.0.1",
        "url-loader": "^1.1.2",
        "vue": "^2.5.17",
        "vue-loader": "^15.4.2",
        "vue-template-compiler": "^2.5.17",
        "webpack": "^4.25.1",
        "webpack-cli": "^3.1.2",
        "webpack-dev-server": "^3.1.10",
        "webpack-merge": "^4.1.4"
      }
    }

webpack.base.config.js

    const path = require('path');       // node路径模块
    const HTMLWebpackPlugin = require('html-webpack-plugin');   // HTML导出模块
    const config = require('../config/pages.config');                   // 多页面配置文件
    const VueLoaderPlugin = require('vue-loader/lib/plugin');   // vue解析模块
    const MiniCssExtractPlugin = require("mini-css-extract-plugin") ;   // css提取模块
    const CleanWebpackPlugin = require('clean-webpack-plugin'); // 删除指定目录模块
    
    let HTMLPlugins = [];
    let Entries = {};
     
    config.HTMLDirs.forEach(item => {
      const htmlPlugin = new HTMLWebpackPlugin({
        title: item.title, // 生成的html页面的标题
        filename: `${item.page}.html`, // 生成到dist目录下的html文件名称,支持多级目录(eg: `${item.page}/index.html`)
        template: path.resolve(__dirname, `../template/index.html`), // 模板文件,不同入口可以根据需要设置不同模板
        chunks: [item.page, 'vendor'], // html文件中需要要引入的js模块,这里的 vendor 是webpack默认配置下抽离的公共模块的名称
        minify: {
            collapseWhitespace: true,    // 压缩空白
            removeAttributeQuotes: true  // 删除属性双引号
        }
      });
      HTMLPlugins.push(htmlPlugin);
      Entries[item.page] = path.resolve(__dirname, `../src/pages/${item.page}/index.js`); // 根据配置设置入口js文件
    });
    
    module.exports = {
        entry: Entries, // 多入口
        output: {
            filename: 'js/[name].[hash:8].js',
            path: path.resolve(__dirname, '../dist'),
            publicPath: ''
        },
        plugins: [
            new VueLoaderPlugin(),  // vue解析器
            new MiniCssExtractPlugin({ // 提取样式到单独的文件中
                filename: "css/[name].[hash:8].css",
                chunkFilename: "[id].css"
            }),
            ...HTMLPlugins  // 多页面输出
        ],
        module: {
            rules: [
                {
                    test: /\.vue$/,
                    exclude: /node_modules/,
                    use: ['vue-loader']
                },
                {
                    test: /\.css$/,
                    exclude: /node_modules/,
                    include: path.join(__dirname, '../src'),
                    use: [
                        {
                            loader: MiniCssExtractPlugin.loader, // 提取less为单独的样式文件\
                            options: {
                                publicPath: '../'
                            }
                        }, 
                        'style-loader', 
                        'css-loader',
                        'postcss-loader'
                    ]
                },
                {
                    test:/\.less$/,
                    exclude: /node_modules/,
                    include: path.join(__dirname, '../src'),
                    use:[
                        {
                            loader: MiniCssExtractPlugin.loader, // 提取less为单独的样式文件\
                            options: {
                                publicPath: '../'
                            }
                        }, 
                        'css-loader',
                        'postcss-loader',
                        'less-loader'
                    ] 
                },
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    include: path.join(__dirname, '../src'),
                    use: ["babel-loader"]
                },
                {
                    test: /\.(png|jpg|jpeg|gif)$/,
                    exclude: /node_modules/,
                    include: path.join(__dirname, '../src'),
                    use: [{
                        loader: "url-loader",
                        options: {
                            name: '[name].[hash:7].[ext]',
                            limit: 10000, // 表示小于10kb的图片转为base64,否则为路径
                            outputPath: "images"
                        }
                    },
    	            {	//压缩图片要在url-loader之后使用
    	            	loader:'image-webpack-loader',
                        options:{
                            bypassOnDebug: true
                        }
    	            }]
                },
                {
                    test: /\.(eot|svg|ttf|woff)$/,
                    exclude: /node_modules/,
                    include: path.join(__dirname, '../src'),
                    use: ['url-loader']
                }
            ]
        },
        // 对控制台输出日志的简化
        stats: {
            modules: false, // 是否添加构建模块信息
            children: false // 是否添加 children 信息
        }
    
    }

webpack.dev.config.js

    const path = require("path");
    const merge = require("webpack-merge");
    const webpackConfigBase = require("./webpack.base.config");
     
    const webpackConfigDev = {
        devtool: 'cheap-module-eval-source-map', // 指定加source-map的方式
        mode: 'development',
        devServer:{
            // 设置服务器访问的基本目录
            contentBase: path.resolve(__dirname,'../dist'), //最好设置成绝对路径
            // 设置服务器的ip地址,可以是localhost
            host: '192.168.60.105',
            // 设置端口
            port: 8090,
            // 设置自动拉起浏览器
            open: false
        },
        watch: true, // 开启监听文件更改,自动刷新
        watchOptions: {
            ignored: /node_modules/, // 忽略不用监听变更的目录
            aggregateTimeout: 500, // 防止重复保存频繁重新编译,500毫米内重复保存不打包
            poll:1000 // 每秒询问的文件变更的次数
        }
    }
    module.exports = merge(webpackConfigBase, webpackConfigDev);

webpack.prod.config.js

const path = require("path");
const webpackConfigBase = require("./webpack.base.config");
const CleanWebpackPlugin = require('clean-webpack-plugin'); // 删除指定目录模块
const merge = require("webpack-merge");
const UglifyjsWebpackPlugin = require("uglifyjs-webpack-plugin");
const optimizeCss = require("optimize-css-assets-webpack-plugin");

const webpackConfigProd = {
    mode: "production",
    plugins: [
        new CleanWebpackPlugin(["dist"], {              // 此处配置根目录
            root: path.resolve(__dirname, '../'),       // 根目录
            verbose:  true,                     // 开启在控制台输出信息
     }), 
        new optimizeCss()
    ],
    externals: {
        vue: 'vue'
    },
    optimization: {
        minimizer: [
            new UglifyjsWebpackPlugin({
                exclude: /\.min\.js$/,
                cache: true,
                parallel: true,
                sourceMap: false,
                extractComments: false,
                uglifyOptions: {
                    compress: {
                        unused: true,
                        warnings: false,
                        drop_debugger: true
                    },
                    output: {
                        comments: false
                    }
                }
            })
        ]
    }
};
module.exports = merge(webpackConfigBase, webpackConfigProd);

目录

这是项目的目录

说明

.babelrc 文件的内容

{
    "presets": ["env"]
}

postcss.config.js 样式添加前缀的配置文件

// 自动添加CSS浏览器前缀,配置文件,设置支持的浏览器类型
// 需要安装 postcss-loader autoprefixer 两个插件
module.exports = {
    plugins: [
        require('autoprefixer')({
            "browsers": [
                "defaults",
                "not ie < 11",
                "last 2 versions",
                "> 1%",
                "iOS 7",
                "last 3 iOS versions"
            ]
        })
    ]
};

config文件夹里的配置是配置多页面的数据。

module.exports = {
    HTMLDirs: [
        {
            page: 'index',
            title: '首页'
        },
        {
            page: 'about',
            title: '关于我们'
        }
    ]
}

template文件夹是存放html模板,可以每个页面一个不同的html模板

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <div id="root"></div>
  </head>
  <body>
  </body>
</html>

注:爱护原创,转载请说明出处

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

云端君

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

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

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

打赏作者

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

抵扣说明:

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

余额充值