美文网首页
webpack多页面应用打包通用方案

webpack多页面应用打包通用方案

作者: 小蜗牛的碎碎步 | 来源:发表于2019-11-21 18:01 被阅读0次
多页面应用(MPA)概念

每次页面跳转的时候,后台服务器都会返回一个新的html文档,这种类型的网站也就是多页网站,也叫做多页应用。

多页面应用优势
  1. 每个页面都是解耦的
  2. SEO更加友好
多页面打包通用方案:动态配置entry对象
const glob = require('glob');
const HTMLWebpackPlugin = require("html-webpack-plugin");

const setMPA = () =>{
    const entry = {};
    const htmlWebpackPlugins = [];
    //匹配src目录下的所有目录
    const entryFiles = glob.sync(path.join(__dirname,'./src/*/index.js'));
    /*
      entryFiles [ '/Users/mac/myProject/my-webpack/src/index/index.js',
    '/Users/mac/myProject/my-webpack/src/search/index.js' ]
    */
    Object.keys(entryFiles).map((index) =>{
        const entryFile = entryFiles[index];
        const match = entryFile.match(/src\/(.*)\/index\.js/);
        //入口页面名称
        const pageName = match && match[1];
        /*
          pageName: index
          pageName: search
        */
        entry[pageName] = entryFile;

        htmlWebpackPlugins.push(
            new HTMLWebpackPlugin({
                //待压缩的文件路径      
               template:path.join(__dirname,`src/${pageName}/index.html`),
                filename:`${pageName}.html`,//打包后的文件名称
                chunks:[pageName],
                inject:true,//是否自动引入相关的css,js文件
                minify:{//是否使用文件压缩
                    html5:true,
                    collapseWhitespace:true,
                    preserveLineBreaks:false,
                    minifyCSS:true,
                    minifyJS:true,
                    removeComments:false
                }
            })
        )
    })
   
    return {
        entry,
        htmlWebpackPlugins
    }
}

const {entry,htmlWebpackPlugins} = setMPA();
//添加插件
module.exports = {
   entry:entry,
  plugins:[
       .....
    ].concat(htmlWebpackPlugins)
}

相关文章

网友评论

      本文标题:webpack多页面应用打包通用方案

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