Home Web Front-end JS Tutorial Detailed explanation of webpack+express multi-page site development examples

Detailed explanation of webpack+express multi-page site development examples

Dec 23, 2017 pm 03:11 PM
web Development example

After studying the webpack entry-level tutorial, I feel that it may be tailor-made for single-page applications, such as webpack+react, webpack+vue, etc., which can solve the dependency loading and packaging problems of various resources. Even css is packaged in js and dynamically added to the dom document. This article mainly introduces the detailed explanation of webpack+express multi-page site development, I hope it can help everyone.

So if we want an ordinary web site with multiple pages, css is independent, and js loading requires modules?

Project address: webpackDemo_jb51.rar

Initialize the project and install dependencies

package.json


"devDependencies": {
  "css-loader": "^0.23.1",
  "extract-text-webpack-plugin": "^1.0.1",
  "file-loader": "^0.8.5",
  "html-loader": "^0.4.3",
  "html-webpack-plugin": "^2.9.0",
  "jquery": "^1.12.0",
  "less": "^2.6.0",
  "less-loader": "^2.2.2",
  "sass-loader": "^4.0.2",
  "style-loader": "^0.13.0",
  "url-loader": "^0.5.7",
  "webpack": "^1.12.13",
  "webpack-dev-server": "^1.14.1"
}
Copy after login

Directory structure (I use the express framework, others are based on personal needs)


- webpackDemo
  - src        #代码开发目录
    - css      #css目录,按照页面(模块)、通用、第三方三个级别进行组织
      + page
      + common
      + lib
    - js       #JS脚本,按照page、components进行组织
      + page
      + components
    + template      #HTML模板
  - node_modules    #所使用的nodejs模块
  - public            #express静态资源文件
    - dist            #webpack编译打包输出目录,无需建立目录可由webpack根据配置自动生成
      + css        
      + js
    + img      #图片资源
  + view            #express静态资源文件(webpack编译打包输出view目录)
  package.json      #项目配置
  webpack.config.js  #webpack配置
Copy after login

Development page

In src/js Create the index.js file in the /page directory and the index.html file in the src/view directory. The entry js corresponds to the template file name.

index.html The content is as follows:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
  <!--
    描述:head中无需再引入css以及facicon,webpack将根据入口JS文件的要求自动实现按需加载或者生成style标签
  -->
</head>
<body>
  <!--
    描述:body中同样无需单独引入JS文件,webpack会根据入口JS文件自动实现按需加载或者生成script标签,还可以生成对应的hash值
  -->
</body>
</html>
Copy after login

is such a simple HTML template. Do not introduce any CSS and JS. It can be automatically packaged through webpack. We introduce.

index.js content is as follows:


//引入css
require("../../css/lib/base.css");
require("../../css/page/index.scss");
$(&#39;body&#39;).append(&#39;<p class="text">index</p>&#39;);
Copy after login

page1.html:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>page1</title>
</head>
<body>
</body>
</html>
Copy after login

page1. js:


//引入css
require("../../css/lib/base.css");
require("../../css/page/page1.less");
$(&#39;body&#39;).html(&#39;page1&#39;);
Copy after login

webpack configuration (I use the express framework, others are based on personal needs)


var path = require(&#39;path&#39;);
var webpack = require(&#39;webpack&#39;);
/*
extract-text-webpack-plugin插件,
有了它就可以将你的样式提取到单独的css文件里,
妈妈再也不用担心样式会被打包到js文件里了。
 */
var ExtractTextPlugin = require(&#39;extract-text-webpack-plugin&#39;);
/*
html-webpack-plugin插件,重中之重,webpack中生成HTML的插件,
具体可以去这里查看https://www.npmjs.com/package/html-webpack-plugin
 */
var HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);

module.exports = {
  entry: { //配置入口文件,有几个写几个
    index: &#39;./src/js/page/index.js&#39;,
    page1: &#39;./src/js/page/page1.js&#39;
  },
  output: { 
    path: path.join(__dirname, &#39;./public/dist/&#39;), //输出目录的配置,模板、样式、脚本、图片等资源的路径配置都相对于它
    publicPath: &#39;/dist/&#39;,        //模板、样式、脚本、图片等资源对应的server上的路径
    filename: &#39;js/[name].js&#39;,      //每个页面对应的主js的生成配置
    chunkFilename: &#39;js/[id].chunk.js&#39;  //chunk生成的配置
  },
  module: {
    loaders: [ //加载器,关于各个加载器的参数配置,可自行搜索之。
      {
        test: /\.css$/,
        //配置css的抽取器、加载器。&#39;-loader&#39;可以省去
        loader: ExtractTextPlugin.extract(&#39;style-loader&#39;, &#39;css-loader&#39;) 
      }, {
        test: /\.less$/,
        //配置less的抽取器、加载器。中间!有必要解释一下,
        //根据从右到左的顺序依次调用less、css加载器,前一个的输出是后一个的输入
        //你也可以开发自己的loader哟。有关loader的写法可自行谷歌之。
        loader: ExtractTextPlugin.extract(&#39;css!less&#39;)
      }, {
        test: /\.scss$/,
        //配置scss的抽取器、加载器。中间!有必要解释一下,
        //根据从右到左的顺序依次调用scss、css加载器,前一个的输出是后一个的输入
        //你也可以开发自己的loader哟。有关loader的写法可自行谷歌之。
        loader: ExtractTextPlugin.extract(&#39;css!scss&#39;)
      }, {
        //html模板加载器,可以处理引用的静态资源,默认配置参数attrs=img:src,处理图片的src引用的资源
        //比如你配置,attrs=img:src img:src就可以一并处理src引用的资源了,就像下面这样
        test: /\.html$/,
        loader: "html?attrs=img:src img:src"
      }, {
        //文件加载器,处理文件静态资源
        test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: &#39;file-loader?name=./fonts/[name].[ext]&#39;
      }, {
        //图片加载器,雷同file-loader,更适合图片,可以将较小的图片转成base64,减少http请求
        //如下配置,将小于8192byte的图片转成base64码
        test: /\.(png|jpg|gif)$/,
        loader: &#39;url-loader?limit=8192&name=./img/[hash].[ext]&#39;
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({ //加载jq
      $: &#39;jquery&#39;
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: &#39;commons&#39;, // 将公共模块提取,生成名为`commons`的chunk
      chunks: [&#39;index&#39;,&#39;page1&#39;], //提取哪些模块共有的部分
      minChunks: 2 // 提取至少2个模块共有的部分
    }),
    new ExtractTextPlugin(&#39;css/[name].css&#39;), //单独使用link标签加载css并设置路径,相对于output配置中的publickPath
    
    //HtmlWebpackPlugin,模板生成相关的配置,每个对于一个页面的配置,有几个写几个
    new HtmlWebpackPlugin({ //根据模板插入css/js等生成最终HTML
      favicon: &#39;./src/favicon.ico&#39;, //favicon路径,通过webpack引入同时可以生成hash值
      filename: &#39;../../views/index.html&#39;, //生成的html存放路径,相对于path
      template: &#39;./src/template/index.html&#39;, //html模板路径
      inject: &#39;body&#39;, //js插入的位置,true/&#39;head&#39;/&#39;body&#39;/false
      hash: true, //为静态资源生成hash值
      chunks: [&#39;commons&#39;, &#39;index&#39;],//需要引入的chunk,不配置就会引入所有页面的资源
      minify: { //压缩HTML文件  
        removeComments: true, //移除HTML中的注释
        collapseWhitespace: false //删除空白符与换行符
      }
    }),
    new HtmlWebpackPlugin({ //根据模板插入css/js等生成最终HTML
      favicon: &#39;./src/favicon.ico&#39;, //favicon路径,通过webpack引入同时可以生成hash值
      filename: &#39;../../views/page1.html&#39;, //生成的html存放路径,相对于path
      template: &#39;./src/template/page1.html&#39;, //html模板路径
      inject: true, //js插入的位置,true/&#39;head&#39;/&#39;body&#39;/false
      hash: true, //为静态资源生成hash值
      chunks: [&#39;commons&#39;, &#39;list&#39;],//需要引入的chunk,不配置就会引入所有页面的资源
      minify: { //压缩HTML文件  
        removeComments: true, //移除HTML中的注释
        collapseWhitespace: false //删除空白符与换行符
      }
    })

    // new webpack.HotModuleReplacementPlugin() //热加载
  ],
  //使用webpack-dev-server,提高开发效率
  // devServer: {
  //   contentBase: &#39;./&#39;,
  //   host: &#39;localhost&#39;,
  //   port: 9090, //默认8080
  //   inline: true, //可以监控js变化
  //   hot: true, //热启动
  // }
};
Copy after login

Okay After completing the above configurations, execute the webpack packaging command to complete project packaging.


Hash: e6219853995506fd132a
Version: webpack 1.14.0
Time: 1338ms
        Asset    Size Chunks       Chunk Names
     js/index.js 457 bytes    0 [emitted] index
     js/page1.js 392 bytes    1 [emitted] page1
    js/commons.js   306 kB    2 [emitted] commons
    css/index.css  62 bytes    0 [emitted] index
    css/page1.css  62 bytes    1 [emitted] page1
   css/commons.css 803 bytes    2 [emitted] commons
     favicon.ico  1.15 kB     [emitted]
../../view/index.html 496 bytes     [emitted]
../../view/page1.html 499 bytes     [emitted]
  [0] ./src/js/page/index.js 170 bytes {0} [built]
  [0] ./src/js/page/page1.js 106 bytes {1} [built]
  + 7 hidden modules
Child html-webpack-plugin for "../../view/page1.html":
    + 1 hidden modules
Child html-webpack-plugin for "../../view/index.html":
    + 1 hidden modules
Child extract-text-webpack-plugin:
    + 2 hidden modules
Child extract-text-webpack-plugin:
    + 2 hidden modules
Child extract-text-webpack-plugin:
    + 2 hidden modules
Copy after login

At this point, go to the views directory to view the generated index.html file, as follows:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>  
<link rel="shortcut icon" href="/dist/favicon.ico" rel="external nofollow" ><link href="/dist/css/commons.css?e6219853995506fd132a" rel="external nofollow" rel="stylesheet"><link href="/dist/css/index.css?e6219853995506fd132a" rel="external nofollow" rel="stylesheet"></head>
<body>
  <script type="text/javascript" src="/dist/js/commons.js?e6219853995506fd132a"></script><script type="text/javascript" src="/dist/js/index.js?e6219853995506fd132a"></script></body>
</html>
Copy after login

You can see that in addition to retaining the content in the original template, the generated file also automatically adds the CSS and JS files that need to be introduced, as well as the favicon according to the definition of the entry file index.js, and also adds the corresponding hash value.

Two questions

  1. How does webpack automatically discover the entry file and configure the corresponding template

  2. How to deal with styles and scripts automatically introducing problems directly


var path = require(&#39;path&#39;);
var webpack = require(&#39;webpack&#39;);
var glob = require(&#39;glob&#39;);
/*
extract-text-webpack-plugin插件,
有了它就可以将你的样式提取到单独的css文件里,
妈妈再也不用担心样式会被打包到js文件里了。
 */
var ExtractTextPlugin = require(&#39;extract-text-webpack-plugin&#39;);
/*
html-webpack-plugin插件,重中之重,webpack中生成HTML的插件,
具体可以去这里查看https://www.npmjs.com/package/html-webpack-plugin
 */
var HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);
/**
 *将公共模块提取,生成名为`commons`的chunk
 */
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
//压缩
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;

//判断开发模式
var debug = process.env.NODE_ENV !== &#39;production&#39;;
var getEntry = function(globPath, pathDir) {
  var files = glob.sync(globPath);
  var entries = {},
    entry, dirname, basename, pathname, extname;
  for (var i = 0; i < files.length; i++) {
    entry = files[i];
    dirname = path.dirname(entry);  //文件目录
    extname = path.extname(entry);  //后缀名
    basename = path.basename(entry, extname); //文件名
    pathname = path.join(dirname, basename);
    pathname = pathDir ? pathname.replace(new RegExp(&#39;^&#39; + pathDir), &#39;&#39;) : pathname;
    entries[pathname] = [&#39;./&#39; + entry]; //这是在osx系统下这样写 win7 entries[basename]
  }
  console.log(entries);
  return entries;
}

//入口(通过getEntry方法得到所有的页面入口文件)
var entries = getEntry(&#39;src/js/page/**/*.js&#39;, &#39;src/js/page/&#39;);
//提取哪些模块共有的部分从entries里面获得文件名称
var chunks = Object.keys(entries);
//模板页面(通过getEntry方法得到所有的模板页面)
var pages = Object.keys(getEntry(&#39;src/template/**/*.html&#39;, &#39;src/template/&#39;));

console.log(pages)

var config = {
  entry: entries,
  output: {
    path: path.join(__dirname, &#39;./public/dist/&#39;),//输出目录的配置,模板、样式、脚本、图片等资源的路径配置都相对于它
    publicPath: &#39;/dist/&#39;,        //模板、样式、脚本、图片等资源对应的server上的路径
    filename: &#39;js/[name].js&#39;,      //每个页面对应的主js的生成配置
    chunkFilename: &#39;js/[id].chunk.js?[chunkhash]&#39;  //chunk生成的配置
  },
  module: {
    loaders: [ //加载器
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(&#39;style&#39;, &#39;css&#39;)
      }, {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract(&#39;css!less&#39;)
      }, {
        test: /\.html$/,
        loader: "html?-minimize"  //避免压缩html,https://github.com/webpack/html-loader/issues/50
      }, {
        test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: &#39;file-loader?name=fonts/[name].[ext]&#39;
      }, {
        test: /\.(png|jpe?g|gif)$/,
        loader: &#39;url-loader?limit=8192&name=imgs/[name]-[hash].[ext]&#39;
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({ //加载jq
      $: &#39;jquery&#39;
    }),
    new CommonsChunkPlugin({
      name: &#39;commons&#39;, // 将公共模块提取,生成名为`commons`的chunk
      chunks: chunks,
      minChunks: chunks.length // 提取所有entry共同依赖的模块
    }),
    new ExtractTextPlugin(&#39;css/[name].css&#39;), //单独使用link标签加载css并设置路径,相对于output配置中的publickPath
    debug ? function() {} : new UglifyJsPlugin({ //压缩代码
      compress: {
        warnings: false
      },
      except: [&#39;$super&#39;, &#39;$&#39;, &#39;exports&#39;, &#39;require&#39;] //排除关键字
    }),
  ]
};

pages.forEach(function(pathname) {
  var conf = {
    filename: &#39;../../views/&#39; + pathname + &#39;.html&#39;, //生成的html存放路径,相对于path
    template: &#39;src/template/&#39; + pathname + &#39;.html&#39;, //html模板路径
    inject: false, //js插入的位置,true/&#39;head&#39;/&#39;body&#39;/false
    /*
    * 压缩这块,调用了html-minify,会导致压缩时候的很多html语法检查问题,
    * 如在html标签属性上使用{{...}}表达式,所以很多情况下并不需要在此配置压缩项,
    * 另外,UglifyJsPlugin会在压缩代码的时候连同html一起压缩。
    * 为避免压缩html,需要在html-loader上配置&#39;html?-minimize&#39;,见loaders中html-loader的配置。
     */
    // minify: { //压缩HTML文件
    // removeComments: true, //移除HTML中的注释
    // collapseWhitespace: false //删除空白符与换行符
    // }
  };
  if (pathname in config.entry) {
    favicon: &#39;./src/favicon.ico&#39;, //favicon路径,通过webpack引入同时可以生成hash值
    conf.inject = &#39;body&#39;;
    conf.chunks = [&#39;commons&#39;, pathname];
    conf.hash = true;
  }
  config.plugins.push(new HtmlWebpackPlugin(conf));
});
module.exports = config;
Copy after login

The following code is similar to the above. The essential difference is that the code is passed through a method. Put all related files into one object and complete the effect of automatic introduction!

The above are all configurations in mac osx system, the win7 path may be different

glob: The parsed here is different:

But the final requirement is


entries:
 {
 index: [ &#39;./src/template/index.js&#39; ],
 page1: [ &#39;./src/template/page1.js&#39; ]
 }

pages:
 [ &#39;index&#39;, &#39;page1&#39; ]
Copy after login

It should be changed accordingly according to the configuration of the personal computer.

Related recommendations:

Front-end engineering development based on webpack - multi-page site (2)_html/css_WEB-ITnose

A brief introduction to getting started with Node.js and Express (pictures and text)

webpack learning tutorial front-end performance optimization summary

The above is the detailed content of Detailed explanation of webpack+express multi-page site development examples. 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)

How to use python+Flask to realize real-time update and display of logs on web pages How to use python+Flask to realize real-time update and display of logs on web pages May 17, 2023 am 11:07 AM

1. Log output to file using module: logging can generate a custom level log, and can output the log to a specified path. Log level: debug (debug log) = 5) {clearTimeout (time) // If all results obtained 10 consecutive times are empty Log clearing scheduled task}return}if(data.log_type==2){//If a new log is obtained for(i=0;i

How to use Nginx web server caddy How to use Nginx web server caddy May 30, 2023 pm 12:19 PM

Introduction to Caddy Caddy is a powerful and highly scalable web server that currently has 38K+ stars on Github. Caddy is written in Go language and can be used for static resource hosting and reverse proxy. Caddy has the following main features: Compared with the complex configuration of Nginx, its original Caddyfile configuration is very simple; it can dynamically modify the configuration through the AdminAPI it provides; it supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure it; it can be expanded to data Tens of thousands of sites; can be executed anywhere with no additional dependencies; written in Go language, memory safety is more guaranteed. First of all, we install it directly in CentO

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

Using Jetty7 for Web server processing in Java API development Using Jetty7 for Web server processing in Java API development Jun 18, 2023 am 10:42 AM

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

How to configure nginx to ensure that the frps server and web share port 80 How to configure nginx to ensure that the frps server and web share port 80 Jun 03, 2023 am 08:19 AM

First of all, you will have a doubt, what is frp? Simply put, frp is an intranet penetration tool. After configuring the client, you can access the intranet through the server. Now my server has used nginx as the website, and there is only one port 80. So what should I do if the FRP server also wants to use port 80? After querying, this can be achieved by using nginx's reverse proxy. To add: frps is the server, frpc is the client. Step 1: Modify the nginx.conf configuration file in the server and add the following parameters to http{} in nginx.conf, server{listen80

Real-time protection against face-blocking barrages on the web (based on machine learning) Real-time protection against face-blocking barrages on the web (based on machine learning) Jun 10, 2023 pm 01:03 PM

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

See all articles