Home > Web Front-end > JS Tutorial > Deepening your understanding of Webpack: Part 2

Deepening your understanding of Webpack: Part 2

王林
Release: 2023-09-06 16:17:13
Original
783 people have browsed it

加深对 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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template