search
HomeWeb Front-endJS TutorialOutput, the core concept of webpack

Output, the core concept of webpack

Aug 09, 2022 pm 06:32 PM
webpackoutput

After gathering all the assets together, you also need to tell webpack where to package the application. The output attribute of webpack describes how to handle bundled code. The following article will give you an in-depth understanding of the output (Output) in the core concept of webpack. I hope it will be helpful to you!

Output, the core concept of webpack

Output: Configuring the output option can control how webpack writes compiled files to the hard disk. Note that even though multiple entry points can exist, only one output configuration is specified.

Start


We first npm init initialize a project and install webpack and webpack locally -cli, then create index.html, webpack.config.js and src folders in the root directory, and create another one inside the folder main.jsAs the entry file

After the preparation work is completed, as shown in the figure:

Output, the core concept of webpack

main. js

function Component(){
    var div=document.createElement('div')
    div.innerHTML="来一起学习出口配置吧~"
    return div
}
document.body.appendChild(Component())

index.html

    <script></script>

packag.json

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "build":"webpack" //加上
},

The next step is the configuration part:webpack.config.js

Output)


Configurationoutput options can control how webpack sends The compiled file is written to the hard disk.

Note that even though there can be multiple entrancesstarting points, only one outputconfiguration

The following are several output configurations Concept:

1, path

path specifies the location of resource output, and the required value must be an absolute path , such as :

const path=require('path')
module.exports={
    entry:'./src/main.js',
    output:{
        filename:'bundle.js',
        //将资源输出位置设置为该项目的dist目录
        path: path.resolve(__dirname, 'dist')
    },
}

After Webpack 4, output.path has defaulted to the dist directory. Unless we need to change it, there is no need to configure it separately, so if it is webpack4 or above, you can write:

module.exports={
    entry:'./src/main.js',
    output:{
        filename:'bundle.js',
    },
}

2, filename

filename The function is to control the file name of the output resource, which is in the form of a string. Here I named it bundle.js, which means I want the resources to be output in a file called bundle.js:

module.exports={
    entry:'./src/main.js',
    output:{
        filename:'bundle.js',
    },
}

As shown in the figure after packaging, a # will be automatically generated. ##dist folder, there is a bundle.js file

Output, the core concept of webpack

filename can be not only the name of the bundle, but also It can be a relative path

It doesn’t matter even if the directory in the path does not exist, Webpack will create the directory when outputting resources, for example:

  module.exports = {
    output: {
      filename: './js/bundle.js',
    },
  };
After packaging, it is like this:

Output, the core concept of webpack

In a multi-entry scenario, we need to specify a different name for each generated bundle. Webpack supports the use of a similar template language Dynamically generate the file name in the form

Before that, we create a new entry file

vender.js in src

:

function Component(){
    var div=document.createElement('div')
    div.innerHTML="我是第二个入口文件"
    return div
}
document.body.appendChild(Component())
webpack.config.js:

module.exports = {
    entry:{
        main:'./src/main.js',
        vender:'./src/vender.js'
    },
    output: {
      filename: '[name].js',
    },
 };
After packaging, as shown in the figure:

Output, the core concept of webpack

[name] in filename will Replaced with chunk name, namely main and vendor. Therefore, vendor.js and main.js

will be generated in the end. If you want to see the content, you still need to

index.htmlChange the content in the middle and match the path to the last packaged bundle

    <script></script>
    <script></script>
[Question] There will be a need at this time, how to make

index.html automatically help What if we add the generated bundle to html? The plug-in HtmlWebpackPlugin can be used here. See the details below

3. Others

except

[name] In addition to chunk name, there are several other template variables that can be used in the configuration of filename:

    [hash]: refers to the hash generated by Webpack for packaging all resources this time
  • [chunkhash]: refers to the hash of the current chunk content
  • [id]: refers to the id of the current chunk
  • [query]: refers to the query
  • in the filename configuration item
They can:

Control client-side caching

[hash] and [chunkhash] are both directly related to chunk content , if used in filename, when the content of the chunk changes, it can also cause the resource file name to change, so that the user will immediately download the new version when requesting the resource file next time without using the local cache.

[query] can also have a similar effect, but it has nothing to do with the chunk content and must be manually specified by the developer.

4、publicPath

publicPath是一个非常重要的配置项,用来指定资源的请求位置

以加载图片为例

import Img from './img.jpg';
function component() {
    //...
    var img = new Image();
    myyebo.src = Img //请求url
	//...
}
        {
          //...
          query: {
            name: '[name].[ext]',
            outputPath: 'static/img/',
            publicPath: './dist/static/img/'
          }
        }

由上面的例子所示,原本图片请求的地址是./img.jpg,而在配置上加上publicPath后,实际路径就变成了了./dist/static/img/img.jpg,这样就能从打包后的资源中获取图片了

publicPath有3种形式:

  • HTML相关

    我们可以将publicPath指定为HTML的相对路径,在请求这些资源时会以当前页面HTML所在路径加上相对路径,构成实际请求的URL

    //假设当前html地址为:https://www.example.com/app/index.html
    //异步加载的资源名为 1.chunk.js
    pubilicPath:"" 		//-->https://www.example.com/app/1.chunk.js
    pubilicPath:"./js" 	//-->https://www.example.com/app/js/1.chunk.js
    pubilicPath:"../assets/"  	//-->https://www.example.com/assets/1.chunk.js
  • Host相关

    若publicPath的值以“/”开始,则代表此时publicPath是以当前页面的host name为基础路径的

    //假设当前html地址为:https://www.example.com/app/index.html
    //异步加载的资源名为 1.chunk.js
    pubilicPath:"/" 	//-->https://www.example.com/1.chunk.js
    pubilicPath:"/js/" 	//-->https://www.example.com/js/1.chunk.js
  • CDN相关

    上面两个都是相对路径,我们也可以使用绝对路径的形式配置publicPath

    这种情况一般发生于静态资源放在CDN上面时,由于其域名与当前页面域名不一致,需要以绝对路径的形式进行指定

    当publicPath以协议头或相对协议的形式开始时,代表当前路径是CDN相关

    //假设当前html地址为:https://www.example.com/app/index.html
    //异步加载的资源名为 1.chunk.js
    pubilicPath:"http://cdn.com/" 	//-->http://cdn.com/1.chunk.js
    pubilicPath:"https://cdn.com/"	//-->https://cdn.com/1.chunk.js
    pubilicPath:"//cdn.com/assets"	//-->//cdn.com/assets/1.chunk.js

应用


1、单个入口

在 webpack 中配置 output 属性的最低要求是将它的值设置为一个对象,包括以下两点:

  • filename 用于输出文件的文件名。
  • 目标输出目录 path 的绝对路径
module.exports={
    entry:'./src/main.js',
    output:{
        filename:'bundle.js',
    },
}
//webpack4以后dist会默认生成,于是这里省略了path

2、多个入口

如果配置创建了多个单独的 "chunk",则应该使用占位符来确保每个文件具有唯一的名称

这里用到了上面所讲的filename的[name]

另外,如果想将这些资源放进指定的文件夹,可以加上path配置

module.exports={
    entry: {
      main: './src/main.js',
      vender: './src/vender.js'
    },
    output: {
      filename: '[name].js',
      path: __dirname + '/dist/assets' //指定打包后的bundle放在/dist/assets目录下
    }
  }
// 打包后生成:./dist/assets/main.js, ./dist/assets/vender.js

HtmlWebpackPlugin


本章上方遗留的问题可以通过使用插件HtmlWebpackPlugin解决

安装插件

npm install --save-dev html-webpack-plugin

配置插件

const HtmlWebpackPlugin=require('html-webpack-plugin') //加载模块
module.exports = {
    entry:{
        main:'./src/main.js',
        vender:'./src/vender.js'
    },
    //添加插件
    plugins:[
        new HtmlWebpackPlugin({
            title:'output management'
        })
    ],
    output: {
      filename: '[name].js',
    },
 };

打包

打包完成后你会发现dist中出现了一个新的index.html,上面自动帮我们添加所生成的资源,打开后会发现浏览器会展示出内容

Output, the core concept of webpack

这意味着,以后初始化一个项目就不必写index.html

源码可从这里获取:

https://sanhuamao1.coding.net/public/webpack-test/webpack-test/git/files

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Output, the core concept of webpack. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor