search
HomeWeb Front-endJS TutorialAbout how webpack configures multiple pages

本篇文章主要介绍了详解webpack多页面配置记录,现在分享给大家,也给大家做个参考。

之前也写过webpack学习记录,项目中需要一个常用的webpack多页面配置,所以才动手,本着能写一行是一行的原则,开始了配置webpack之旅。

定目录结构

首先我只需要开发环境(包含自动更新)和打包环境,初定的目录结构是这样的

app主要写业务代码,config里写webpack配置和一些打包、开发的配置,经过一番计较,最后根据自己习惯,目录结构如下:

 

app
 -libs # 第三方插件库,可以是css也可以是js,eg:jq
 -static # 公共的静态资源文件夹
 -temlates # 模板文件夹
  -*** # 模块文件夹
  -css # 当前模块独有的css文件需要在index.js中import
  -html # 模板文件,计划支持html,pug两种模板语言
  -index.js # 当前模块入口文件

配置webpack

按上面所说,建好文件后,在根目录新建webpack.config.js

然后全局安装webpack和webpack-dev-server

npm i webpack webpack-dev-server -g

然后局部安装

npm i webpack webpack-dev-server --save-dev

这样我们的项目就可以引入webpack了,并且可以使用webpack-dev-server的相关功能了,webpack.config.js内容非常的简单,就是根据环境变量中指定的当前环境来加载不同的webpack配置即可:

// 未指定这手动指定为生产环境
process.env.NODE_ENV = process.env.NODE_ENV ? process.env.NODE_ENV : 'product';
// 获取环境命令,并去除首尾空格
const env = process.env.NODE_ENV.replace( /(\s*$)|(^\s*)/ig, "" );
// 根据环境变量引用相关的配置文件
module.exports = require( `./config/webpack.config.${env}.js` )

在config文件夹下分别新建webpack.config.dev.js和webpack.config.product.js分别代表开发环境的配置和生成打包文件的配置,考虑到很多配置都会相同,再建一个webpack.config.base.js用来写统一的配置。

webpack.config.dev.js和webpack.config.product.js的区别是一个runtime时的配置,一个文件生成的配置,简而言之,就是开发环境的不同是配置webpack-dev-server,生产环境是压缩,map等配置

webpack.config.base.js文件才是webpack配置的主菜,包括entry、output、modules、plugins等

获得所有入口文件的文件夹

function getEntryDir() {
  let globPath = 'app/templates/**/*.' + config.tplLang
  // (\/|\\\\) 这种写法是为了兼容 windows和 mac系统目录路径的不同写法
  let pathDir = 'app(\/|\\\\)(.*?)(\/|\\\\)html'
  let files = glob.sync( globPath )
  let dirname, entries = []
  for ( let i = 0; i < files.length; i++ ) {
    dirname = path.dirname( files[ i ] )
    entries.push( dirname.replace( new RegExp( &#39;^&#39; + pathDir ), &#39;$2&#39; ) )
  }
  return entries;
}

注入entry和生成HTMLWebpackPlugin

getEntryDir()
  .forEach( ( page ) => {
    let moduleName = page.split( &#39;/&#39; )
    let moduleNameStr = moduleName[ moduleName.length - 1 ]
    const htmlPlugin = new HTMLWebpackPlugin( {
      filename: `${moduleNameStr}.html`,
      template: path.resolve( __dirname, `../app/${page}/html/index.${config.tplLang}` ),
      chunks: [ moduleNameStr, &#39;vendors&#39; ],
    } );
    HTMLPlugins.push( htmlPlugin );
    Entries[ moduleNameStr ] = path.resolve( __dirname, `../app/${page}/index.js` );
  } )

关于HTMLWebpackPlugin的用法,可以参照html-webpack-plugin用法全解 以及 官方文档 已经写的非常详尽了。

第三方库入口自动获取

function getVendors() {
  let globPath = `app/${config.libraryDir}/**/*.*`
  let files = glob.sync( globPath )
  let libsArr = []
  files.forEach( ( v, i ) => {
    libsArr.push( &#39;./&#39; + v )
  } )
  return libsArr
}
Entries[ &#39;vendors&#39; ] = getVendors() // 第三方类库

其中多页面入口和第三方库配置,请看这篇webpack中文站文档分离 应用程序(app) 和 第三方库(vendor) 入口

output 配置

output: {
 filename: "static/js/[name].bundle.[hash].js",
 path: path.resolve( __dirname, config.devServerOutputPath )
}

webpack配置合并

主要用到一个webpack插件 webpack-merge,可把分开配置的config合并,分开生产环境和调试环境

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

pace.js和NProgress.js如何使用加载进度插件(详细教程)

在微信小程序中有关页面生命周期详细解读(详细教程)

在Vue中如何实现服务器渲染Nuxt

在vue中如何使用Nprogress.js进度条

详细讲解Vue单元测试中Karma+Mocha

The above is the detailed content of About how webpack configures multiple pages. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment