Home Web Front-end JS Tutorial How to implement multi-page development in webpack

How to implement multi-page development in webpack

Jun 20, 2018 am 10:39 AM
webpack

This article mainly introduces the practice of webpack multi-page development. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

Written in front

webpack is a module loader and packaging tool that can convert js, css, pages, pictures, Various resources such as videos are modularized. Nowadays, there are many single-page webpack models circulating on the Internet, but what about multiple pages? Less so, now I offer a multi-page front-end model. Hope everyone can use it.

When I first came into contact with webpack, I thought webpack was only suitable for single-page applications, such as webpack react and webpack vue. I myself feel the power and convenience of webpack in the process of using webpack vue to build projects and develop. Based on actual project needs, I am wondering whether multi-page sites can also be built using webapck? So I started some exploration and finally built a relatively complete solution.

This article takes an actual project as an example to describe how to use webpack for engineering construction in multi-page projects. This article is a summary of my own practical experience, so some solutions are not optimal and are still being explored and optimized. If there are any errors or omissions, please point them out.

Introduction

This project is mainly built based on webpack2.x, with gulp as an auxiliary tool. The front end uses art-template as the template engine. One page corresponds to a template file and an entry file. Other modules can be introduced into the entry file through import or require. Webpack will automatically merge these modules into one file with the entry file.

Front-end development environment setup

Main directory structure

├─dist          #打包后生成的文件目录
└─src           #开发目录
  ├─components     #通用组件
  ├─static       #静态资源目录
  │ ├─css
  │ ├─img
  │ └─js
  │   ├─component  #站点通用组件对应的js
  │   ├─lib     #第三方js库
  │   ├─services   #各页面入口
  │   └─util     #通用工具js
  ├─template      #html模板
  └─views        #页面
   main.js       #公共入口
gulpfile.js        #gulp任务配置
package.json       #项目依赖
webpack.config.js     #webpack配置
Copy after login

webpack configuration

Entry file

// 获取入口文件
var entries = (function() {
  var jsDir = path.resolve(__dirname, 'src/static/js/services');
  var entryFiles = glob.sync(jsDir + '/*.js');
  var map = {};

  entryFiles.forEach(function(filePath) {
    var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
    map[filename] = filePath;
  });
  return map;
})();
Copy after login

This method will generate a map from the file name to the absolute path of the file, such as

entry: {
  'page-1': '/../webpack-multipage-demo/src/static/js/services/page-1.js'
}
Copy after login

Hot update

Hot update is simply not easy to use, greatly Improved development efficiency.

//服务器配置
var devServer = env === 'production' ? {} : {
  contentBase: path.resolve(__dirname),
  compress: true,
  historyApiFallback: true,
  hot: true,
  inline: true,
  host: 'localhost', 
  port: 8080
};
Copy after login

In addition, add new webpack.HotModuleReplacementPlugin() to the plugin and enable Hot Module Replacemen to achieve hot updates.

Generate html configuration

It is agreed that the js file on the same page has the same name as the template file, and finally an html file with the same name is generated based on the js.

var htmlPages = (function() {
  var artDir = path.resolve(__dirname, 'src/views');
  var artFiles = glob.sync(artDir + '/*.art');
  var array = [];
  artFiles.forEach(function(filePath) {
    var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
    array.push(new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src/template/index.html'),
      filename: filename + '.html',
      chunks: ['vendor', 'main', filename],
      chunksSortMode: function(chunk1, chunk2) {
        var order = ['vendor', 'main', filename];
        var order1 = order.indexOf(chunk1.names[0]);
        var order2 = order.indexOf(chunk2.names[0]);
        return order1 - order2;
      },
      minify: {
        removeComments: env === 'production' ? true : false,
        collapseWhitespace: env === 'production' ? true : false
      }
    }));
  });
  return array;
})();
Copy after login

Extract common modules into components

For some modules that need to be used in multiple pages, they can be extracted as common components. The composition of the component is the same as that of the page, a .js file, a .art file and a .css file. The html content is rendered in the js file and finally exported. You can directly require it when using it. For specific practices, please refer to demo

Existing problems

  1. Every time a new page is created, the webpack service needs to be restarted

  2. Font files cannot be compressed. There is currently no better solution for compressing web fonts introduced through font-face

demo

A demo based on the theory of this article, address: webpack-multipage-demo

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement the number input box component in Vue

How to use jquery to achieve the left and right sidebar scaling effect

Detailed introduction to setTimeout in JS function

Detailed introduction to updating objects in mongoose

How to implement AOP in JavaScript

The above is the detailed content of How to implement multi-page development in webpack. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VUE3 Getting Started Tutorial: Packaging and Building with Webpack VUE3 Getting Started Tutorial: Packaging and Building with Webpack Jun 15, 2023 pm 06:17 PM

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

What is the difference between vite and webpack What is the difference between vite and webpack Jan 11, 2023 pm 02:55 PM

Differences: 1. The startup speed of the webpack server is slower than that of Vite; because Vite does not require packaging when starting, there is no need to analyze module dependencies and compile, so the startup speed is very fast. 2. Vite hot update is faster than webpack; in terms of HRM of Vite, when the content of a certain module changes, just let the browser re-request the module. 3. Vite uses esbuild to pre-build dependencies, while webpack is based on node. 4. The ecology of Vite is not as good as webpack, and the loaders and plug-ins are not rich enough.

How to use PHP and webpack for modular development How to use PHP and webpack for modular development May 11, 2023 pm 03:52 PM

With the continuous development of web development technology, front-end and back-end separation and modular development have become a widespread trend. PHP is a commonly used back-end language. When doing modular development, we need to use some tools to manage and package modules. Webpack is a very easy-to-use modular packaging tool. This article will introduce how to use PHP and webpack for modular development. 1. What is modular development? Modular development refers to decomposing a program into different independent modules. Each module has its own function.

How does webpack convert es6 to es5 module? How does webpack convert es6 to es5 module? Oct 18, 2022 pm 03:48 PM

Configuration method: 1. Use the import method to put the ES6 code into the packaged js code file; 2. Use the npm tool to install the babel-loader tool, the syntax is "npm install -D babel-loader @babel/core @babel/preset- env"; 3. Create the configuration file ".babelrc" of the babel tool and set the transcoding rules; 4. Configure the packaging rules in the webpack.config.js file.

Use Spring Boot and Webpack to build front-end projects and plug-in systems Use Spring Boot and Webpack to build front-end projects and plug-in systems Jun 22, 2023 am 09:13 AM

As the complexity of modern web applications continues to increase, building excellent front-end engineering and plug-in systems has become increasingly important. With the popularity of Spring Boot and Webpack, they have become a perfect combination for building front-end projects and plug-in systems. SpringBoot is a Java framework that creates Java applications with minimal configuration requirements. It provides many useful features, such as automatic configuration, so that developers can build and deploy web applications faster and easier. W

What files can vue webpack package? What files can vue webpack package? Dec 20, 2022 pm 07:44 PM

In vue, webpack can package js, css, pictures, json and other files into appropriate formats for browser use; in webpack, js, css, pictures, json and other file types can be used as modules. Various module resources in webpack can be packaged and merged into one or more packages, and during the packaging process, the resources can be processed, such as compressing images, converting scss to css, converting ES6 syntax to ES5, etc., which can be recognized by HTML. file type.

What is Webpack? Detailed explanation of how it works? What is Webpack? Detailed explanation of how it works? Oct 13, 2022 pm 07:36 PM

Webpack is a module packaging tool. It creates modules for different dependencies and packages them all into manageable output files. This is especially useful for single-page applications (the de facto standard for web applications today).

An in-depth analysis of the packaging process and principles of webpack An in-depth analysis of the packaging process and principles of webpack Aug 09, 2022 pm 05:11 PM

How does Webpack implement packaging? The following article will give you an in-depth understanding of Webpack packaging principles. I hope it will be helpful to you!

See all articles