美文网首页
webpack4入门配置(多页面)

webpack4入门配置(多页面)

作者: 谢_ffd1 | 来源:发表于2019-02-18 11:05 被阅读0次

安装webpack相关组件

安装
npm install --save-dev webpack
安装
npm install --save-dev webpack-cli
安装
npm install --save-dev webpack-merge
安装
npm install --save-dev webpack-dev-server

配置中会使用到你的插件及加载器

安装
npm install --save-dev html-webpack-plugin
安装
npm install copy-webpack-plugin --save-dev
安装
npm install clean-webpack-plugin --save-dev
  • mini-css-extract-plugin 此插件将CSS提取到单独的文件中。它为每个包含CSS的JS文件创建一个CSS文件(webpack4推荐使用css插件)
安装
npm install --save-dev mini-css-extract-plugin
安装
npm install uglifyjs-webpack-plugin --save-dev
安装
npm install --save-dev optimize-css-assets-webpack-plugin

目录结构

|--src
    |--assets
    |--css
    |--image
    |--js
    |--tool
    |--views
    |--common.js
    |--favicon.ico
    |--index.css
    |--index.html
    |--main.js
|--.babelrc
|--package.json
|--package-lock.json
|--postcss.config.js
|--webpack.base.conf.js
|--webpack.dev.conf.js
|--webpack.prod.conf.js

配置

webpack.base.conf.js

const path = require('path');//引入nodejs路径模块, 用于操作文件路径。
const glob = require('glob');//引入glob, 用于解析路径(查找文件)
const webpack = require("webpack");//引入webpack, 用于访问webpack内置插件
const HtmlWebpackPlugin = require('html-webpack-plugin');//通过模板生成html页面的插件(用于生成html页面)
const copyWebpackPlugin = require("copy-webpack-plugin");//静态资源输出(原始输出不编译)

//检索目录拼接入口
function getEntry(){
    var entry = {"main": './src/main.js',"wx":'./src/common.js'};
    //检索src/views目录下index.js =》  index.js父目录名称作为入口key, index.js所在路径作为入口路径
    glob.sync(__dirname+'/src/views/**/@(index).js').forEach(function (name) {
        var start = name.indexOf('/');
        var end =  name.lastIndexOf('/');
        var n = name.slice(start,end);
        var start1 = n.lastIndexOf('/')+1;
        var end1 =  n.length;
        var key = n.slice(start1,end1);
        entry[key] = name;
    });
    return entry;
};

//入口
let entry = getEntry();

//HtmlWebpackPlugin
function getHtml(){
    var plugins=[];
    for(var i in entry ){
        var start = entry[i].indexOf('src')+4;
        var end = entry[i].lastIndexOf('/');
        var pathStr = entry[i].slice(start,end);
        if(i=='wx'){
            plugins.push(
                new HtmlWebpackPlugin({
                    favicon: path.resolve(__dirname, 'src/favicon.ico'),//添加网页图标
                    title: "",//添加网页标题
                    chunks: [i,"code"],
                    filename: path.resolve(__dirname, `dist/insurance-mall/wx.html`),
                })
            );
        }else{
            plugins.push(
                new HtmlWebpackPlugin({
                    favicon: path.resolve(__dirname, 'src/favicon.ico'),//添加网页图标
                    title: "",//添加网页标题
                    'meta': {//添加meta属性
                        'viewport': 'width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no',
                        'renderer': 'webkit',
                        'X-UA-Compatible': {'http-equiv': 'X-UA-Compatible', 'content': 'IE=Edge'},
                        'MSThemeCompatible': {'http-equiv': 'MSThemeCompatible', 'content': 'Yes'},
                        'imagetoolbar': {'http-equiv': 'imagetoolbar', 'content': 'No'},
                        'format-detection': 'email=no,telephone=no',
                        'MSSmartTagsPreventParsing': 'True',
                        'Access-Control-Allow-Origin': '*',
                        'keywords': '',
                        'description': ''
                    },
                    chunks: [i,'code'],
                    filename:path.resolve(__dirname, `dist/insurance-mall/${pathStr==''?'index':pathStr}.html`),
                    template: path.resolve(__dirname, `src/${pathStr}/index.html`)
                })
            );
        }
    };
    return plugins;
};

//HtmlWebpackPlugin
let plugins = getHtml();

module.exports = {
    //入口文件的配置项
    entry:entry,
    //出口文件的配置项
    output: {
        //所有输出文件的目标路径
        path: path.resolve(__dirname, 'dist/insurance-mall')
    },
    //插件,用于生产模板和各项功能
    plugins: [
        //自动加载模块
        new webpack.ProvidePlugin({
            $: "jquery", //如:在模块中使用$('#item'); // <= 起作用会自动加载jquery
            jQuery: "jquery",
            Vue: ['vue/dist/vue.esm.js', 'default']
        }),
        //不编译输出
        // new copyWebpackPlugin([{
        //     from: path.resolve(__dirname, "src/assets"),
        //     to: './pulic'
        // }]),
        ...plugins
    ],
    //模块:例如解读CSS,图片如何转换,压缩
    module: {
        rules: [
            {
                test: /\.(jsx|js)$/,
                use: {
                    loader: 'babel-loader'  //会自动使用根目录下的.babelrc配置文件
                },
                include: path.resolve(__dirname, "src"),//检索src目录下的.jsx|.js文件并使用babel-loader加载器加载
                exclude: path.resolve(__dirname, "node_modules") //不检索node_modules目录下的.jsx|.js文件
            },
            {
                test: /\.(htm|html)$/i,
                use: [{
                        loader: 'html-withimg-loader'
                    }, {
                        loader: 'html-loader',
                        options: {
                            attrs: ['img:data-original', 'img:src']
                        }
                    }]
            },
            {
                test: /\.(png|svg|jpg|gif|jpeg)$/,
                use: [{
                    loader: 'url-loader', //是指定使用的loader和loader的配置参数
                    options: {
                        limit: 500,  //是把小于500B的文件打成Base64的格式,写入JS
                        name: "[hash:8].[name].[ext]",
                        outputPath: 'images',  //打包后的图片放到images文件夹下
                    }
                }, {
                    loader: 'image-webpack-loader'
                }]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    'file-loader'
                ]
            },
            {
                test: /\.(csv|tsv)$/,
                use: [
                    'csv-loader'
                ]
            },
            {
                test: /\.xml$/,
                use: [
                    'xml-loader'
                ]
            }
        ]
    },
    //解析模块请求的选项
    resolve: {
        alias: {
            "@src": path.resolve("src"),
            "@images": path.resolve("src/images")
        }
    },
    optimization: {
        splitChunks: {
            chunks: 'all',
            name:false,
            cacheGroups: {
                commons: {
                    name: 'code',
                    chunks: 'initial',
                    minChunks: 2    //分割前必须共享模块的最小块数。
                }
            }
        },
        removeAvailableModules: true,//当这些模块已包含在所有父项中时,告诉webpack检测并从块中删除模块
        removeEmptyChunks: true,//告诉webpack检测并删除空的块
        mergeDuplicateChunks: true,//告诉webpack合并包含相同模块的块
    }
    //context: path.resolve(__dirname, 'src')    //指定编译基本目录
};

webpack.dev.conf.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.base.conf.js');

module.exports = merge(common, {
    //出口文件的配置项
    output: {
        // 「入口分块(entry chunk)」的文件名模板(出口分块?)  //打包的文件名称
        filename:'js/[name].js',
        // 输出解析文件的目录,url 相对于 HTML 页面
        publicPath: "http://localhost:80/insurance-mall/"
    },
    devtool: 'inline-source-map',
    devServer: {
        //设置基本目录结构,用于找到程序打包地址
        contentBase:path.join(__dirname,'dist'),
        //服务器的IP地址,可以使用IP也可以使用localhost
        host:'localhost',
        //在所有响应中添加首部内容
        headers: {
            "Access-Control-Allow-Origin": "*"
        },
        open:true,
        //服务端压缩是否开启
        //compress:true,
        //绕过主机检查
        disableHostCheck: true,
        //网络广播服务器
        //bonjour: true,
        //此选项允许浏览器使用您的本地IP打开
        useLocalIp: false,
        //配置服务端口号
        port:80,
        //是否开启热重载
        hot: true
    },
    plugins: [
        new webpack.NamedModulesPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [{
                    loader: "style-loader"
                }, {
                    loader: "css-loader"
                }, {
                    loader: "postcss-loader"
                }]
            },
            {
                test: /\.less$/,
                use: [{
                    loader: "style-loader"
                },{
                    loader: "css-loader"
                }, {
                    loader: "less-loader"
                }]
            },
            {
                test: /\.scss$/,
                use: [{
                    loader: "style-loader"
                }, {
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }]
            }
        ]
    },
    mode: "development"

webpack.prod.conf.js

const merge = require('webpack-merge');//用于合并webpack配置
const CleanWebpackPlugin = require('clean-webpack-plugin');// 清除目录等(dist)
const MiniCssExtractPlugin = require("mini-css-extract-plugin");//提取css(webpack4支持)
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");//压缩
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");//缩小输出css
const common = require('./webpack.base.conf.js');

module.exports = merge(common, {
    //出口文件的配置项
    output: {
        // 「入口分块(entry chunk)」的文件名模板(出口分块?)  //打包的文件名称
        filename:'js/[name].[chunkhash].js',
        publicPath: " "
    },
    plugins: [
        //清理打包代码目录
        new CleanWebpackPlugin(['dist']),
        new MiniCssExtractPlugin({
            filename: 'css/[name].[contenthash].css'
        }),
    ],
    module: {
        rules:[
            {
                test: /\.css$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader
                }, {
                    loader: "css-loader"
                }, {
                    loader: "postcss-loader"
                }]
            },
            {
                test: /\.less$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader
                },{
                    loader: "css-loader"
                },{
                    loader: "postcss-loader"
                }, {
                    loader: "less-loader"
                }]
            },
            {
                test: /\.scss$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader
                }, {
                    loader: "css-loader"
                },{
                    loader: "postcss-loader"
                }, {
                    loader: "sass-loader"
                }]
            }
        ]
    },
    optimization: {
        minimizer: [
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: true
            }),
            new OptimizeCSSAssetsPlugin({})
        ]
    },
    mode:"production"
});

.babelrc

{
  "presets": ["@babel/preset-react", "@babel/preset-env"]
}

postcss.config.js

module.exports={
    plugins: [
        require('autoprefixer') //自动添加前缀插件
    ]
}

相关文章

网友评论

      本文标题:webpack4入门配置(多页面)

      本文链接:https://www.haomeiwen.com/subject/zpobdqtx.html