As we all know, native WebPack only supports JS and JSON file types (this is webPack’s built-in capability). If you want to use other types of resources, you need to use various Loaders or asset Modules. Here’s how WebPack parses several common resources.

babel-loader

Webpack only supports JavaScript files. What if you want to use ES6/ES7, React JSX, or Vue? Babel-loader was born for this purpose. Babel-loader allows us to translate JavaScript files using Babel and Webpack.

Use ES6 and React JSX as an example to introduce how to use babel-loader.

First, install babel-loader:

npm i babel-loader -D
Copy the code

Then, in the webpack configuration file (webpack.config.js), add the usage rule of babel-loader: use babel-loader to parse matched JS files.

// webpack.config.js

module.exports = {
  // ...
  module: {
    rules: [{ test: /\.js$/, use: "babel-loader"}],}};Copy the code

Babel-loader is dependent on Babel, so Babel needs to be configured (.babelrc).

Parsing ES6

Install PRESET to parse ES6:

npm i @babel/core @babel/preset-env -D
Copy the code

Add to.babelrc:

{
  "presets": ["@babel/preset-env"]}Copy the code

You can add a file that contains the ES6 syntax and pack it (NPX webpack) to see the effect:

SRC/index. Js:

const user = { name: "juejin" };
function hello({ name }) {
  document.write(`hello ${name}`);
}

hello(user);
Copy the code

Dist /index.js:

document.write("hello ".concat("juejin"));
Copy the code

Parsing the React JSX

Install the react:

npm i react react-dom -S
Copy the code

Install preset to parse React JSX:

npm i @babel/preset-react -D
Copy the code

Add to.babelrc:

{
  "preset": [
    "@babel/preset-env",
  + "@babel/preset-react"]}Copy the code

This allows us to parse a JSX syntax file:

src/search.js

import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(<h1>Hello, world!</h1>.document.getElementById("root"));
Copy the code

Add an HTML file to the dist directory generated by the package and hang it in the parsed JSX file:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="./search.js"></script>
  </body>
</html>
Copy the code

CSS – loader and style – loader

Parsing the CSS

To parse CSS files in webpack, use csS-loader and style-loader.

  • css-loaderUsed to load.cssFile, and converted into a CommomJS object to be inserted into the JS code.
  • style-loaderResponsible for passing the style through<style>Tag inserted intoheadIn the.

Install csS-loader and style-loader:

npm i css-loader style-loader -D
Copy the code

Then configure the rules for parsing.css files in webpack.config.js:

module.exports = {
  // ...
  module: {
    rules: [{ test: /\.css$/, use: ["style-loader"."css-loader"]}],}};Copy the code

[“style-loader”, “style-loader”] [“style-loader”, “style-loader”] [“style-loader”, “style-loader”]

Parse Less/Sass

In the daily development process, less/sass is more powerful and practical. Webpack is also very simple to parse less/sass. Take.less files as an example, you only need to add a less-loader:

  • less-loaderTo convert less to CSS

Less-loader depends on less. Therefore, install less and less-loader first.

npm i less less-loader -D
Copy the code

Then, the configuration in webpack.config.js:

module.exports = {
  // ...
  module: {
    rules: [{test: /\.less$/, use: ["style-loader"."css-loader"."less-loader"]},],},};Copy the code

We can import less files one at a time in the previous search.js file and see what happens:

search.js

import React from "react";
import ReactDOM from "react-dom";
import "./search.less";

ReactDOM.render(
  <h1 className="search-text">
    Hello, <span>world!</span>
  </h1>.document.getElementById("root"));Copy the code

search.less

.search-text {
  color: red;
  span {
    color: green; }}Copy the code

NPX webpack packed effect, no problem:

Parsing resource files (images, fonts, etc.)

Before WebPack 5, it was common to use:

  • raw-loaderImport the file as a string
  • url-loaderInline the file as a data URI into the bundle
  • file-loaderSend the file to the output directory

In WebPack 5, all of these loaders are replaced by adding four new module types:

  • asset/resourceSend a separate file and export the URL. Previously by usingfile-loaderThe implementation.
  • asset/inlineExport the data URI of a resource. Previously by usingurl-loaderThe implementation.
  • asset/sourceExport the source code of the resource. Previously by usingraw-loaderThe implementation.
  • assetAutomatically choose between exporting a data URI and sending a separate file. Previously by usingurl-loaderAnd configure the resource volume limitation implementation.

We will introduce the usage of the two methods respectively by analyzing pictures and texts

Use file-loader to parse images

The installation file – loader:

npm i file-loader -D
Copy the code

Configuration in webpack.config.js:

module.exports = {
  / /...
  module: {
    // ...
    rules: [{ test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"]}],}};Copy the code

Add a test image logo.png to the SRC /assets directory, then import and display this image in search.js:

import React from "react";
import ReactDOM from "react-dom";
import "./search.less";
+ import logo from "./assets/logo.png";

ReactDOM.render(
  <h1 className="search-text">
    Hello, <span>world!</span>
+    <img src={logo} />
  </h1>.document.getElementById("root"));Copy the code

After NPX webpack is packed, the dist directory will generate the parsed image, the file name is the image Hash:

Use the resource module to parse fonts

Using the resource module, our configuration item changes by changing use: ‘file-loader’ to type: ‘asset/resource’ :

module.exports = {
  // ...
  module: {
    rules: [
      // ...
      { test: /\.(woff|woff2|eot|ttf|otf)$)/, type: "asset/resource"},],}};Copy the code

Add a test font in SRC/Assets, such as titanone.ttf (a free English font you can find anywhere), and add it to search.less:

@font-face {
  font-family: "TradeWinds";
  src: url("./assets/TradeWinds.ttf");
}

.search-text {
  color: red;
  font-family: "TradeWinds";
  span {
    color: green; }}Copy the code

After NPX webpack is packed, the dist directory will generate the parsed font:

Look at the actual page effect, the font display is normal:

Webpack series

  • preface
  • Extremely brief introduction
  • The core concept
  • Parse the file
  • File listening and hot update
  • File fingerprint Policy
  • Code compression
  • CSS enhancement: Autoprefixer
  • Multi-page Application Packaging Solution (MPA)