Table of Contents
Style Loader
You have to yell at it
picture
Preloader
准备生产
摘要
Home Web Front-end JS Tutorial Deepening your understanding of Webpack: Part 2

Deepening your understanding of Webpack: Part 2

Sep 06, 2023 pm 04:17 PM

加深对 Webpack 的理解:第 2 部分

In the previous tutorial, we learned how to set up a Webpack project and how to use a loader to handle JavaScript. Where Webpack really shines, though, is its ability to bundle other types of static resources (such as CSS and images) and include them in our projects only when needed. Let's start by adding some styling to the page.

Style Loader

First, create a normal CSS file in the styles directory. Call main.css and add style rules for the title element.

h2 {
    background: blue;
    color: yellow;
}
Copy after login

So how do we put this stylesheet into our page? Well, like most things with Webpack, we need another loader. There are actually two: css-loader and style-loader. The first one reads all the styles from our CSS file, while the other injects said styles into our HTML page. Install them like this:

npm install style-loader css-loader
Copy after login

Next, we tell Webpack how to use them. In webpack.config.js we need to add another object to the loaders array. In it, we're going to add a test to match only CSS files and specify the loader to use.

{
    test: /\.css$/,
    exclude: /node_modules/,
    loader: 'style!css'
}
Copy after login

The interesting part of this code snippet is the 'style!css' line. The loader reads from right to left, so this tells Webpack to first read the styles of any file ending with .css and then inject those styles into our page.

Because we have updated the configuration file, we need to restart the development server for the changes to take effect. Use ctrl c to stop the server and use webpack-dev-server to restart the server.

All we need to do now is get the stylesheet from the main.js file. We do this the same way as any other JavaScript module:

const sayHello = require('./say-hello');

require('./styles/main.css');

sayHello('Guybrush', document.querySelector('h2'));
Copy after login

Note that we haven't even touched index.html. Open the browser and you will see a page with the style h2. Changing the color of the header in the stylesheet updates immediately without refreshing. cute.

You have to yell at it

"But no one uses CSS these days, Grandpa! It's all about Sass." Of course. Luckily, Webpack has a loader that does just that. Install it along with the node version of Sass using the following command:

npm install sass-loader node-sass
Copy after login

Then update webpack.config.js:

{
    test: /\.scss$/,
    exclude: /node_modules/,
    loader: 'style!css!sass'
}
Copy after login

Now what this means is that for any file ending in .scss, convert Sass to plain CSS, read the styles from the CSS, and then insert the styles into the page. Remember to rename main.css to main.scss and require the newly named file. First some Sass:

$background: blue;

h2 {
    background: $background;
    color: yellow;
}
Copy after login

Then main.js:

require('./styles/main.scss');
Copy after login

super. It's that simple. No need to convert and save files or even look at folders. We just need to enter the Sass style directly.

picture

"So I bet the same goes for images and loaders?" Of course! For images, we're going to use url-loader. This loader gets the relative URL of the image and updates the path so that it is included correctly in your package. as usual:

npm install url-loader
Copy after login

Now, let's try something different in webpack.config.js. Add another entry to the loaders array in the usual way, but this time we want the regular expression to match images with different file extensions:

{
    test: /\.(jpg|png|gif)$/,
    include: /images/,
    loader: 'url'
}
Copy after login

Please note another difference here. We are not using the exclude key. Instead, we use include. This is more efficient because it tells webpack to ignore anything that doesn't match a folder named "images".

Normally you would use some kind of templating system to create HTML views, but we're going to keep it basic and create the image markup in JavaScript the old-fashioned way. First create an image element, set the required image to the src attribute, and then add the element to the page.

var imgElement = document.createElement('img');

imgElement.src = require('./images/my-image.jpg');

document.body.appendChild(imgElement);
Copy after login

Return to the browser and your image will appear in front of you!

Preloader

Another task often performed during development is linting. Linting is a method of finding potential errors in your code and checking that you are following certain coding conventions. What you might want to look for is "Did I use a variable without declaring it first?" or "Did I forget the semicolon at the end of the line?" By enforcing these rules, we can weed out silly mistakes early on.

JSHint 是一种流行的 linting 工具。这会检查我们的代码并突出显示我们所犯的潜在错误。 JSHint 可以在命令行手动运行,但这很快就会成为开发过程中的一件苦差事。理想情况下,我们希望它在每次保存文件时自动运行。我们的 Webpack 服务器已经在留意变化,所以是的,你猜对了——另一个加载器。

按照通常的方式安装jshint-loader:

 npm install jshint-loader
Copy after login

我们必须再次将其添加到我们的 webpack.config.js 中来告诉 Webpack 使用它。然而,这个加载器略有不同。它实际上并没有转换任何代码——只是看看。我们也不希望所有较重的代码修改加载器仅仅因为忘记了分号而运行并失败。这就是预加载器的用武之地。预加载器是我们指定在主要任务之前运行的任何加载器。它们以与加载器类似的方式添加到我们的 webpack.conf.js 中。

module: {
    preLoaders: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'jshint'
        }
    ],
    loaders: [
       ...    
    ]
}
Copy after login

现在,如果检测到问题,我们的 linting 过程会立即运行并失败。在重新启动 Web 服务器之前,我们需要告诉 JSHint 我们正在使用 ES6,否则当它看到我们正在使用的 const 关键字时将会失败。

在配置中的模块键之后,添加另一个名为“jshint”的条目和一行来指定 JavaScript 的版本。

module: {
    preLoaders: [
        ...
    ],
    loaders: [
        ...    
    ]
},
jshint: {
    esversion: 6
}
Copy after login

保存文件并重新启动webpack-dev-server。运行还好吗?伟大的。这意味着您的代码不包含错误。让我们通过删除这一行中的分号来介绍一个:

var imgElement = document.createElement('img')
Copy after login

再次保存文件并查看终端。现在我们得到了这个:

WARNING in ./main.js
jshint results in errors
  Missing semicolon. @ line 7 char 47
Copy after login

谢谢,JSHint!

准备生产

现在我们很高兴我们的代码已经成型并且它完成了我们想要的一切,我们需要为现实世界做好准备。上线代码时最常见的事情之一就是缩小代码,将所有文件连接成一个,然后将其压缩到尽可能小的文件中。在继续之前,请查看您当前的 bundle.js。它可读,有大量空白,大小为 32kb。

“等等!别告诉我。另一个装载机,对吧?”没有!在这种罕见的情况下,我们不需要装载机。 Webpack 内置了缩小功能。一旦您对代码感到满意,只需运行以下命令:

webpack -p
Copy after login

-p 标志告诉 Webpack 让我们的代码为生产做好准备。当它生成捆绑包时,它会尽可能地进行优化。运行此命令后,打开 bundle.js,您会看到它全部被压缩在一起,即使使用如此少量的代码,我们也节省了 10kb。

摘要

我希望这个由两部分组成的教程能让您有足够的信心在自己的项目中使用 Webpack。请记住,如果您想在构建过程中执行某些操作,那么 Webpack 很可能有一个加载器。所有加载器都是通过 npm 安装的,因此请查看那里是否有人已经制作了您需要的内容。

玩得开心!

The above is the detailed content of Deepening your understanding of Webpack: Part 2. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles