webpack4打包多文件
发布日期:2021-06-27 14:32:32 浏览次数:5 分类:技术文章

本文共 2610 字,大约阅读时间需要 8 分钟。

webpack4打包多文件

//引包

var path = require("path"); //需要使用绝对路径  var HtmlWebpackPlugin= require("html-webpack-plugin");  const webpack=require("webpack");  const {CleanWebpackPlugin} = require('clean-webpack-plugin')  var glob  = require("glob")

//打包单文件

module.exports= {    entry:{        index:'./src/index.js'    },    output:{        path: path.join(__dirname, 'dist'),        filename: 'js/index.js'    }    ...    plugins:[        new HtmlWebpackPlugin({            filename: 'index.html',            template: './src/index.html',            hash: true,            minify: {                removeAttributeQuotes:true,                removeComments: true,                collapseWhitespace: true,                removeScriptTypeAttributes:true,                removeStyleLinkTypeAttributes:true            }        })    ]}

//打包多文件

webpack.config.js :

function getView(globPath,flag){    let files = glob.sync(globPath);    let entries = {},    entry, dirname, basename, pathname, extname;    files.forEach(item => {        entry = item;        dirname = path.dirname(entry);//当前目录        extname = path.extname(entry);//后缀        basename = path.basename(entry, extname);//文件名        pathname = path.join(dirname, basename);//文件路径        if (extname === '.html') {            entries[pathname] = './' + entry;        } else if (extname === '.js') {            entries[basename] = entry;        }    });    return entries;}

//打包html

let pages = Object.keys(getView('./src/*html'));let htmlPlugins = []pages.forEach(pathname => {    let htmlname = pathname.split('src\\')[1];    let conf = {        filename: `${htmlname}.html`,        template: `${pathname}.html`,        hash: true,        chunks:[htmlname],        minify: {            removeAttributeQuotes:true,            removeComments: true,            collapseWhitespace: true,            removeScriptTypeAttributes:true,            removeStyleLinkTypeAttributes:true        }    }    htmlPlugins.push(new HtmlWebpackPlugin(conf));});module.exports= {mode: 'production', // 这里写成线上环境,开发环境则切换成 development  entry: jsEntries,  output: {    // 静态资源文件的本机输出目录    path: path.resolve(__dirname, 'build'),    // 静态资源服务器发布目录    publicPath: '/',    // 入口文件名称配置    filename: '[name]-[chunkhash].js',    chunkFilename: '[name]-[chunkhash].js'  },  module: {    rules: [      {        test: /\.pug$/,        use: 'pug-loader'      },      {        test: /\.jsx?$/,        use: 'babel-loader?cacheDirectory',        exclude: /node_modules/      }    ]  },       ...      plugins:[      		 ...htmlPlugins,      ]       }

可以参考:

https://www.izhongxia.com/posts/44724.html

转载地址:https://blog.csdn.net/weixin_43799793/article/details/103020130 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:grunt的使用
下一篇:前端面试题(二),不断完善中。。。

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年03月26日 06时11分16秒