webpack打包多页面的方法

2022-10-22,,,

前言

一开始接触webpack是因为使用vue的关系,因为vue的脚手架就是使用webpack构建的。刚开始的时候觉得webpack就是为了打包单页面而生的,后来想想,这么好的打包方案,只在单页面上使用是否太浪费资源了呢?如果能在传统多页面上使用webpack,开始效率是否会事半功倍呢?好在众多优秀的前端开发者已经写了许多demo和文章供人学习。我也写了一个小项目,希望对大家学习webpack有帮助。

好吧其实上面说的都是废话,接下来附上项目地址和干货,配合食用更佳。

webpack-multi-page

项目解决的问题

  • spa好复杂,我还是喜欢传统的多页应用怎么破?又或是,我司项目需要后端渲染,页面模板怎么出?
  • 每个页面相同的ui布局好难维护,ui稍微改一点就要到每个页面去改,好麻烦还容易漏,怎么破?
  • 能不能整合进eslint来检查语法?
  • 能不能整合postcss来加强浏览器兼容性?
  • 我可以使用在webpack中使用jquery吗?
  • 我可以使用在webpack中使用typescript吗?

src目录对应dist目录

当我们使用webpack打包多页面,我们希望src目录对应打包后dist目录是如上图这样的,开发根据页面模块的思路搭建开发架构,然后经过webpack打包,生成传统页面的构架。

/**
 * 创建打包路径
 */
const createfiles = function() {
 const usepug = require('../config').usepug;
 const usetypescript = require('../config').usetypescript;
 const path = require('path');
 const glob = require('glob');
 const result = [];
 const type = usepug ? 'pug' : 'html';
 const scripttype = usetypescript ? 'ts' : 'js';
 const files = glob.sync(path.join(__dirname, `../src/views/**/*.${type}`));
 for (file of files) {
  result.push({
   name: usepug ? file.match(/\w{0,}(?=\.pug)/)[0] : file.match(/\w{0,}(?=\.html)/)[0],
   templatepath: file,
   jspath: file.replace(type, scripttype),
   stylepath: file.replace(type, 'stylus')
  });
 }
 return result;
};

利用这个方法,我们可以获得需要打包的文件路径(方法中获取文件路径的模块也可使用fs模块),根据获得打包的文件路径,我们可以使用html-webpack-plugin来实现多页面打包。

由于每一个html-webpack-plugin的对象实例都只针对/生成一个页面,因此,我们做多页应用的话,就要配置多个html-webpack-plugin的对象实例:

const plugins = function() {
 const files = createfiles();
 const htmlwebpackplugin = require('html-webpack-plugin');
 const path = require('path');
 const extracttextplugin = require('extract-text-webpack-plugin');

 let htmlplugins = [];
 let entries = {};
 files.map(file => {
  htmlplugins.push(
   new htmlwebpackplugin({
    filename: `${file.name}.html`,
    template: file.templatepath,
    chunks: [file.name]
   })
  );
  entries[file.name] = file.jspath;
 });

 return {
  plugins: [
   ...htmlplugins,
   new extracttextplugin({
    filename: getpath => {
     return getpath('css/[name].css');
    }
   })
  ],
  entries
 };
};

由于我使用了extracttextplugin,因此这些css代码最终都会生成到所属chunk的目录里成为一个css文件。

模版引擎

每个页面相同的ui布局好难维护,ui稍微改一点就要到每个页面去改,好麻烦还容易漏,怎么破?

考虑到这个问题,项目引进并使用了pug模版引擎。

现在,我们可以利用pug的特性,创建一个共用组件:

demo.pug

p 这是一个共用组件

然后,当你需要使用这个公用组件时可以引入进来:

include 'demo.pug'

除此之外,你还可以使用一切pug特供的特性。

webpack中配置pug也很简单,先安装:

npm i --save-dev pug pug-html-loader

然后将所有.html后缀的改为.pug后缀,并且使用pug语法。

然后在规则中再增加一条配置

{
  test: /\.pug$/,
  use: 'pug-html-loader'
}

同时把plugins对象中的用到index.html的htmlwebpackplugin中的template,也要改成index.pug。

webpack整合eslint

先放出配置代码:

if (useeslint) {
 loaders.push({
  test: /\.js$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [path.resolve(__dirname, 'src')],
  options: {
   formatter: require('stylish')
  }
 });
}

通过webpack整合eslint,我们可以保证编译生成的代码都是没有语法错误且符合编码规范的;但在开发过程中,等到编译的时候才察觉到问题可能也是太慢了点儿。

因此我建议可以把eslint整合进编辑器或ide里,像我本人在用vs code,就可以使用一个名为eslint的插件,一写了有问题的代码,就马上会标识出来。

dev环境与prod环境

首先,阅读webpacl项目的时候通常要先看package.json这个文件。因为当你在命令行敲下一句命令

npm run dev

webpack就会找到package.json文件中的script属性并依次分析命令,可见,这句命令相应的会执行

复制代码 代码如下:nodemon --watch build/ --exec \"cross-env node_env=development webpack-dev-server --color --progress --config build/webpack.dev.js\"

同样的,当写下命令

npm run build

script就会执行

ross-env node_env=production webpack --config build/webpack.prod.js

这样就能区分开发环境,或是生产环境了。

虽然我们会为环境做区分,但是基于不重复原则,项目为两个环境公用的配置整合到了(build/webpack.base.js)文件中。然后利用webpack-merge插件将配置整合在一起

webpack中使用jquery

在webpack中使用jquery也很简单,我们可以在loaders中增加一条配置:

if (usejquery) {
 loaders.push({
  // 通过require('jquery')来引入
  test: require.resolve('jquery'),
  use: [
   {
    loader: 'expose-loader',
    // 暴露出去的全局变量的名称 随便你自定义
    options: 'jquery'
   },
   {
    // 同上
    loader: 'expose-loader',
    options: '$'
   }
  ]
 });
}

然后当你需要在某个js文件使用jq时,引用暴露出来的变量名即可:

import $ from 'jquery';

webpack中使用typescript

在webpack中使用jquery也很简单,我们可以在loaders中增加一条配置:

if (usets) {
 loaders.push({
  test: /\.tsx?$/,
  use: 'ts-loader',
  exclude: /node_modules/
 });
}

然后将js文件改为ts即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《webpack打包多页面的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。