webpack4打包多文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值