webpack学习笔记(二):基本属性管理

325 阅读2分钟

前言

这是我学习webpack的第二篇学习笔记,前文指路:

  • webpack学习笔记(一):初次见面,请多关照 前一篇博客介绍了webpack的基本概念和从零开始搭建webpack工程的方法。在这一篇博客中,我想讲的是webpack的基本属性管理,主要有两个:资源管理、输出管理。在这篇文章中,继续沿用第一篇文章的示例。

资源管理

可以加载和识别javascript文件和html文件是webpack开箱自带的功能。然而,在一个运行在浏览器的APP中,仅仅能够使用JavaScript和html是不够的,还需要加载一些其他的资源,例如图片,CSS样式文件,以及各种类型的数据文件等等。关于这些文件的加载问题,webpack提供的解决方案是在项目中安装其他的 loader 工具,并且在配置文件中对已安装的工具进行引用。

预处理

首先,对之前的项目做一个简单的小修改

  • dist/index.html
 <!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
  -  <title>起步</title>
  +  <title>管理资源</title>
   </head>
   <body>
  -  <script src="main.js"></script>
  +  <script src="bundle.js"></script>
   </body>
 </html>
  • webpack.config.js
 const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
 -   filename: 'main.js',
 +   filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 }

加载CSS

  1. 通过一下命令行安装必要的模块:style-loader和css-loader

npm install --save-dev style-loader css-loader

  1. 配置webpack.config.js
 const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
     filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 + module: {
 +   rules: [
 +     {
 +       test: /\.css$/i,
 +       use: ['style-loader', 'css-loader'],
 +     },
 +   ],
 + },
 };
  1. 在src文件夹下面添加.CSS文件 改变之后的目录结构如下:
webpack-demo
| - package.json
| - webpack.config.js
| - /dist
    | - bundle.js
    | - index.html
| - /src
    | - style.css
    | - index.js
| - /node_modules
  1. 添加并引入样式
  • CSS
.hello {
    color: red;
  }
  • index.js
import _ from 'lodash'
import './style.css'

function component() {
    const element = document.createElement('div');
  
    // lodash 在当前的 script 中使用 import 引入
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.classList.add('hello');
  
    return element;
  }
  
  document.body.appendChild(component());
  1. 运行npm命令进行打包

npm run build 打包之后,用浏览器打开index.html文件,会发现字体变成红色

加载image图像

更改webpack.config.js文件:

const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
     filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
   module: {
     rules: [
       {
         test: /\.css$/i,
         use: ['style-loader', 'css-loader'],
       },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
     ],
   },
 };

接下来,直接引用所需的图片即可

加载fonts字体

更改webpack.config.js文件:

const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
     filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
   module: {
     rules: [
       {
         test: /\.css$/i,
         use: ['style-loader', 'css-loader'],
       },
       {
         test: /\.(png|svg|jpg|jpeg|gif)$/i,
         type: 'asset/resource',
       },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
      },
     ],
   },
 };

加载数据

  1. 安装相应的loader工具

npm install --save-dev csv-loader xml-loader

  1. 更改webpack.config.js文件
 const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
     filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
   module: {
     rules: [
       {
         test: /\.css$/i,
         use: ['style-loader', 'css-loader'],
       },
       {
         test: /\.(png|svg|jpg|jpeg|gif)$/i,
         type: 'asset/resource',
       },
       {
         test: /\.(woff|woff2|eot|ttf|otf)$/i,
         type: 'asset/resource',
       },
      {
        test: /\.(csv|tsv)$/i,
        use: ['csv-loader'],
      },
      {
        test: /\.xml$/i,
        use: ['xml-loader'],
      },
     ],
   },
 };

总结

关于webpack进行资源管理的问题,只需要两步:

  1. 安装相应的 *-loader 工具(如果有的话)
  2. 在webpack.config.js中进行配置:
module: {
     rules: [
       {
         test: /\.css$/i,     // 这里匹配文件的类型
         use: ['style-loader', 'css-loader'],        // 这里声明需要调用的loader工具
       },
       
     ],
   },

输出管理

在很多项目的开发中,打包后只生成一个文件是不够的,需要同时生成多个js文件。这个时候就需要对webpack的输出进行管理。对于输出的管理,主要有四个方面:

  1. 输出文件管理
  2. 自动生成index.html文件
  3. 清理/dist文件夹
  4. 生成manifest文件(关于这个部分的内容,暂时不讨论)

输出文件管理

  1. 调整项目目录
webpack-demo
| - package.json
| - webpack.config.js
| - /dist
| - /src
    | - index.js
    | - print.js
| - /node_modules
  1. 更改文件内容
  • src/print.js
export default function printMe() {
  console.log('I get called from print.js!');
}
  • src/index.js
import _ from 'lodash';
import printMe from './print.js';

 function component() {
   const element = document.createElement('div');
  const btn = document.createElement('button');

   element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  btn.innerHTML = 'Click me and check the console!';
  btn.onclick = printMe;

  element.appendChild(btn);

   return element;
 }

 document.body.appendChild(component());
  • dist/index.html
<!DOCTYPE html>
 <html>
   <head>
     <meta charset="utf-8" />
    <title>管理输出</title>
    <script src="./print.bundle.js"></script>
   </head>
   <body>
    <script src="./index.bundle.js"></script>
   </body>
 </html>
  1. 配置webpack.config.js
const path = require('path');

 module.exports = {
  entry: {
    index: './src/index.js',
    print: './src/print.js',
  },
   output: {
    filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 };

自动生成index.html文件

  1. 安装插件

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

  1. 配置webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
  plugins: [
    new HtmlWebpackPlugin({
      title: '管理输出',
    }),
  ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
 };

清理/dist文件夹

直接配置webpack.config.js的输出项即可

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

 module.exports = {
   entry: {
     index: './src/index.js',
     print: './src/print.js',
   },
   plugins: [
     new HtmlWebpackPlugin({
       title: 'Output Management',
     }),
   ],
   output: {
     filename: '[name].bundle.js',
     path: path.resolve(__dirname, 'dist'),
     clean: true,
   },
 };