English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Comprehensive analysis of using webpack to build multi-page applications

There are many articles about Webpack configuration and usage on the internet, most of which are about single-page applications. When we need to package multiple html files, things become麻烦起来. How to package multiple html files in webpack-dev-Use routing in server? How to package multiple html and js chunks and automatically update md5?This article is about how to solve these problems.

Here it is assumed that you have a basic understanding of Webpack

Requirements

Let's take a look at our requirements:

  1. Use webpack-dev-Server used for development
  2. In webpack-dev-Use routing in server, access/a is displayed when a.html is shown,/b is displayed when b.html is shown
  3. Pack into multiple html files and add md to the resources referenced5Tap

Main directory structure

├── src            
│  └── views         # Each folder corresponds to a page
│    └── a         
│      └── index.js
│    └── b         
│      └── index.js
├── output          # The directory for packaged output
|  └── ...
└── template.html       # This template will be used to generate the html for each page
└── webpack.config.js
└── dev-server.js       # webpack-dev-server + express    

Only the main directories are listed here. We generate multiple pages' html based on a template.html, and they only differ in the resource paths they reference. Of course, you can also use a separate html template for each page.

Webpack Configuration

Here we mainly solve two small problems.

1Pack multiple pages' js files

Read src/The directories under views, each directory is treated as a page and packed into a js chunk.

2Pack multiple html files

Loop to generate multiple HtmlWebpackPlugin plugins, and point each plugin's chunks to the above packed js chunk.

// webpack.config.js
var glob = require('glob');
var webpackConfig = {
  /* Some basic webpack configurations */  
};
// Get the entry files under the specified path
function getEntries(globPath) {
   var files = glob.sync(globPath),
    entries = {};
   files.forEach(function(filepath) {
     // Take the second-to-last layer (the folder under view) as the package name
     var split = filepath.split('/');
     var name = split[split.length - 2];
     entries[name] = '.',/' + filepath;
   });
   return entries;

var entries = getEntries('src/view/**/index.js');
Object.keys(entries).forEach(function(name) {
  // Generate an entry for each page, if you need HotUpdate, modify the entry here
  webpackConfig.entry[name] = entries[name];
  // Generate an html for each page
  var plugin = new HtmlWebpackPlugin({
    // The generated html filename
    filename: name + '.html',
    // 每个html的模版,这里多个页面使用同一个模版
    template: './template.html',
    // 自动将引用插入html
    inject: true,
    // 每个html引用的js模块,也可以在这里加上vendor等公用模块
    chunks: [name]
  });
  webpackConfig.plugins.push(plugin);
}

路由配置

在多页应用下,我们希望访问的是localhost:8080/a,而不是localhost:8080/a.html。

由于webpack-dev-server只是将文件打包在内存里,所以你没法在express里直接sendfile('output/views/a.html'),因为这个文件实际上还不存在。还好webpack提供了一个outputFileStream,用来输出其内存里的文件,我们可以利用它来做路由。

注意,为了自定义路由,你可能需要引进express或koa之类的库,然后将webpack-dev-server作为中间件处理。

// dev-server.js
var express = require('express')
var webpack = require('webpack')
var webpackConfig = require('./webpack.config')
var app = express();
// webpack编译器
var compiler = webpack(webpackConfig);
// webpack-dev-server中间件
-dev-middleware
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  
});
app.use(devMiddleware)
// Route
app.get('/:viewname? function(req, res, next) {
  var viewname = req.params.viewname 
    ? req.params.viewname + '.html' 
    : 'index.html';
  var filepath = path.join(compiler.outputPath, viewname);
  // Use the outputFileSystem provided by webpack
  compiler.outputFileSystem.readFile(filepath, function(err, result) {
    if (err) {
      // something error
      return next(err);
    
    res.set('content-type/html');
    res.send(result);
    res.end();
  });
});
module.exports = app.listen(8080, function(err) {
  if (err) {
    // do something
    return;
  
  console.log('Listening at http://localhost: + port + '\n')
}

Finally, define the startup command in package.json:

// package.json
{
  scripts: {
    "dev": "node ."/dev-server.js  
  

Run npm run dev, then visit localhost: in the browser8080/On each page, you should be able to see the result you want.

That's all for this article, I hope it will be helpful to everyone's learning, and I also hope that everyone will support Yelling Tutorial more.

Declaration: The content of this article is from the network, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo manual editing, and does not assume relevant legal liability. If you find content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (when sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You may also like