Home > Web Front-end > JS Tutorial > body text

Analysis of steps to build multi-page applications with webpack

php中世界最好的语言
Release: 2018-04-14 10:25:39
Original
1827 people have browsed it

This time I will bring you an analysis of the steps for building a multi-page application with webpack. What are the precautions for building a multi-page application with webpack? The following is a practical case, let's take a look.

Regarding the configuration and use of webpack, there are many articles on the Internet, most of which are about single-page applications. When we need to package multiple html, things become troublesome. How to use routing in webpack-dev-server? How to package multiple html and js chunk and automatically update md5? This article talks about how to solve these problems.

It is assumed here that you already have the most basic understanding of Webpack

need

Let’s take a look at our needs:

  1. Use webpack-dev-server as a development server

  2. Use routing in webpack-dev-server. When accessing /a, a.html is displayed, and /b displays b.html
  3. Package into multiple html, add md5 stamp to the referenced resources
Main

Directory structure

├── src            
│  └── views         # 每一个文件夹对应一个页面
│    └── a         
│      └── index.js
│    └── b         
│      └── index.js
├── output          # 打包输出的目录
|  └── ...
└── template.html       # 将根据这个模版,生成各个页面的html
└── webpack.config.js
└── dev-server.js       # webpack-dev-server + express
Copy after login
Only the main directories are listed. Here we generate HTML for multiple pages based on a template.html. Only the referenced resource paths are different between them. Of course, you can also use a separate HTML template for each page.

Webpack Configuration

There are two main problems to solve here.

1. Package js files for multiple pages

Read the directories under src/views, agree that each directory is treated as a page, and packaged into a js chunk.

2. Pack multiple html

Generate multiple HtmlWebpackPlugin plug-ins in a loop, and point the chunks of each plug-in to the js chunk packaged above.

// webpack.config.js
var glob = require('glob');
var webpackConfig = {
  /* 一些webpack基础配置 */  
};
// 获取指定路径下的入口文件
function getEntries(globPath) {
   var files = glob.sync(globPath),
    entries = {};
   files.forEach(function(filepath) {
     // 取倒数第二层(view下面的文件夹)做包名
     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) {
  // 每个页面生成一个entry,如果需要HotUpdate,在这里修改entry
  webpackConfig.entry[name] = entries[name];
  
  // 每个页面生成一个html
  var plugin = new HtmlWebpackPlugin({
    // 生成出来的html文件名
    filename: name + '.html',
    // 每个html的模版,这里多个页面使用同一个模版
    template: './template.html',
    // 自动将引用插入html
    inject: true,
    // 每个html引用的js模块,也可以在这里加上vendor等公用模块
    chunks: [name]
  });
  webpackConfig.plugins.push(plugin);
})
Copy after login

Routing configuration

In a multi-page application, we want to access localhost:8080/a instead of localhost:8080/a.html.

Since webpack-dev-server only packages files in memory, you cannot directly sendfile('output/views/a.html') in express because the file does not actually exist yet. Fortunately, webpack provides an outputFileStream to output files in its memory. We can use it for routing.

Note that in order to

define routes yourself, you may need to introduce libraries such as express or koa, and then process webpack-dev-server as middleware.

// 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中间件
var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  }
});
app.use(devMiddleware)
// 路由
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);
  
  // 使用webpack提供的outputFileSystem
  compiler.outputFileSystem.readFile(filepath, function(err, result) {
    if (err) {
      // something error
      return next(err);
    }
    res.set('content-type', 'text/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')
})
Copy after login
Finally, define the startup command in package.json:

// package.json
{
  scripts: {
    "dev": "node ./dev-server.js"  
  }
}
Copy after login
Run

npm run dev, and then visit localhost:8080/each page in the browser, you should be able to see what you want result. ​​​​​​​​

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

ajax directly changes the state and deletes the non-refresh state

Where does this point when vue uses axios

Detailed explanation of the use of JS’s multi-threaded runtime library Nexus.js

The above is the detailed content of Analysis of steps to build multi-page applications with webpack. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!