search
HomeWeb Front-endJS TutorialWhat should newbies get started with Webpack?

What should newbies get started with Webpack?

Jun 26, 2017 pm 03:24 PM
webwebpackGetting Started Tutorialstudynewbienotes

WebpackGetting Started Tutorial(Study Notes)

1 Introduction This tutorial is not in-depth and removes a lot of complicated

things. The record also insists on the simplest, so that beginners can have a general understanding of

webpackHave a simple understanding of the system, and it is better to further learn in depthwebpack.

##Webpack is a

Javscript

's packaging program, webpack will automatically analyze the dependencies between each module, and then package these dependencies into one or more files.

##webpackThe most powerful thing is that it can pass Official and third-party plug-ins and loaders(loader)

are used to parse and compile various files.

WebpackThe four most important core concepts: Entry( entry)

, output

(output), loader(loader), plug-in(plugin), below I will try to explain a few by taking notes. The meaning of this concept. If you want to go deeper or if you don’t understand something in your notes, you can check it in the documentation on the official website.

#2

、entry

(entry)webpack The entry of is equivalent to the index file of a web page. With the entry file,

webpack

will know where to start. webpack will use this entry The file analyzes all the files that the entry file depends on, and then packages all the dependent files into one or more files. ##provided by webpack

Single entry syntax and object syntax are included. The single entry syntax is also the simplest one, with only one entry file, one in and one out. For example, the one below.

1 {2   entry: './index.js'3 }

Object syntax is mainly for applications with multiple pages. It tells webpack that there are three entry files. When the packaging is completed There are also three files. These three files are independent of each other. Each file only contains the files it depends on. For example:

1  {2   entry: {3    hello1: './hello1.js',4    hello2: './hello2.js'5   }6  }

 

 

3、输出(output)

webpack提供了output属性,来控制webpack如何把编译好的文件写入到硬盘中,输入和输出是对应的,有输入就有输出。但是必须注意一点,可以存在多个输入,但是只能存在一个输出,那怎么来输出多个独立的编译好的文件呢?webpack中当然有应对的机制。

 

webpack要求output属性为对象,并且必须包含两个属性:filenamepath。顾名思义filename即输出文件的文件名,而path则为输出文件的绝对路径(注意,path必须为决定路径)

 

单个入口output属性写法:

1 {2     entry: './index.js',3     output: {4       path: path.resolve(__dirname, 'app'), //path为nodejs自身的库。__dirname为nodejs在运行过程中的一个环境变量,里面是当前文件夹的完整目录名。resolve方法是把相对路径的app目录解析为一个决定路径。5 6      filename: 'bundle.js'7  }8 }

 

webpack内置了多个变量来应对多个入口文件,如[name][hash][id][chunkhash],通过变量来保证每个文件的唯一性来达到生成多个文件,在生成过程中webpack会把这几个变量替换为相应的字符串用于保证文件的唯一性。

 

多个入口output属性写法:

1 {2     entry: './index.js',3     output: {4         path: path.resolve(__dirname, 'app'),5         filename: [name]-[hash]-bundle.js6      }7 }

 

 

4、加载器(loader)

loader可以对不同类型的文件进行编译转换,比如jsxtypescript直接拿在浏览器上运行是不能运行的,那么我们在编写程序的时候需要借助jsx以及typescript等高效的库来提高我们编写程序的效率,但是我们又需要能正常使用,如果每种文件类型我们都通过一种转换工具,那么就显的很麻烦,所以laoder就是来处理这样的工作。

 

首先在使用loader的时候我们需要安装相应的插件,比如es2015,那我们安装babel-loader,如果是css,那我们安装css-loader,通过下面的module属性里面的rules数组来对需要转换的文件设置loader

 

 1 { 2     entry: './index.js', 3     output: { 4         path: path.resolve(__dirname, 'app'), 5         filename: [name]-[hash]-bundle.js 6     }, 7     module: { 8         rules : [ 9             {test: /\.js$/, use: 'babel-loader'}10          ]11      }12 }

 

上面的rules是一个数组,每个元素是一个对象,对象里面包含了两个属性testusetest的值是一个正则表达式,它的作用是将当前loader用于什么文件,这里正则表达式就是用来匹配你需要转换的文件类型,use是当前匹配到的文件用什么加载器来转换、编译。

 

有三种方式来使用loader加载器

1webpack配置文件

2require语句中使用

3、通过命令行使用

 

第一种上面我们已经说了,下面简单的介绍一下第二种和第三种,第二种使用方法是我们在require或者import文件的时候可以直接使用,比如下面的代码:

 

1 require('babel-loader!./hello.js')

或者

1 Import('babel-loader!./hello.js')

 

第三种方式是直接通过webpack提供的命令行工具—module-bind使用,比如下面的代码:

1 webpack —module-bind 'js=babel-loader'

 

5、插件(plugin)

插件用于解决loader无法解决的事情,比如给每个js文件进行添加著作标记、压缩文件等功能,每个插件都可能有参数选项,每个插件在使用的时候也必须使用new操作符来建立一个插件的实例。插件通过plugins属性来设置,plugins是一个数组,每个元素代表一个插件的实例。因为插件有官方的还有第三方的,所以不会一一去说怎么使用,只是给大家简单演示一下,大家需要用到哪个插件再去查这个插件的api

 

 1 const HtmlWebpackPlugin = require('html-webpack-plugin'); 2 //首先要使用插件,必须先引入插件 3   4 { 5   entry: './index.js', 6   output: { 7    path: path.resolve(__dirname, 'app'), 8    filename: [name]-[hash]-bundle.js 9    },10   module: {11     rules : [12        {test: /\.js$/, use: 'babel-loader'}13     ]14    },15    plugins: [16     new HtmlWebpackPlugin({telmplate : './index.html'})  //通过plugins来使用你需要使用插件。17    ]18 }

6、总结

通过上面的学习,你可以了解到webpack的四个核心,入口、输出、加载器、插件,入口就是你要编译的是哪个文件,指定了过后webpack会自行寻找依赖的文件打包编译。输出就是编译转换好了过后把文件写入到硬盘的哪里。加载器就是对不同类型的文件转换,从而让浏览器能直接运行。插件做的是loader无法解决的事情。

 

 

其实webpack的配置并没有想象中的那么复杂,webpack的配置文件就是一个js文件,只要对webpack有一个系统的认识后,你就知道我该从哪里下手,该从哪里入手了。

 

 

 

 

The above is the detailed content of What should newbies get started with Webpack?. 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
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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 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 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment