webpack快速入门

22,888 阅读3分钟

webpack是一个静态模块打包工具,基于node.js开发。在开启webpack coding之前,我们先了解一些核心概念。

一. 核心概念

  1. Entry 主入口,用来告诉webpack从哪个模块开始,它会找出哪些模块或库是入口模块(直接或间接)的依赖

  2. Output 告诉 webpack 在哪里输出它所创建的 bundle,以及如何命名这些文件

  3. Loader 在webpack中,万物皆模块。它本身只能理解 json和js文件。loader 让 webpack 能够去处理其他类型的文件,并将它们转换为有效模块,以供应用程序使用,以及被添加到依赖图中。 比如: xx.vue, xx.ts, xx.scss 模块,需要使用对应的loader,转化为 webpack 认识的格式。 loader具有以下特性:

  • loader可以是同步的,也可以是异步的。
  • loader可以在nodejs中执行
  • loader支持链式调用,一组链式loader将按照相反顺序执行。链中的第一个 loader 将其结果(也就是应用过转换后的资源)传递给下一个 loader,依此类推。最后,链中的最后一个 loader,返回 webpack 所期望的 JavaScript。
  1. Plugin loader 用于转换某些类型的模块,而插件则可以用于执行范围更广的任务。包括:打包优化,资源管理,注入环境变量等。

  2. Mode 构建模式,告诉webpack是开发环境还是生产环境。 通过选择 development, production 或 none 之中的一个,来设置 mode 参数。

  3. 浏览器兼容 webpack 支持所有符合 ES5 标准 的浏览器(不支持 IE8 及以下版本)

  4. 运行环境 运行环境是node.js。有许多刚入门的小伙伴,误认为是浏览器,在此提醒下~

准备工作ok,下面我们进入奇妙的webpack之旅吧~

二. hello world

下面,我们先初始化一个项目,执行:

npm init test
touch webpack.config.js index.html index.js index.css
yarn add -D webpack@4.43.0 webpack-cli@3.3.11 html-webpack-plugin@4.3.0

编辑index.html

<html>
	<head>
		<meta charset="utf-8"/>
	</head>

	<body>
        <div id='root' class="root"></div>
	</body>
</html>

编辑index.js

console.log("hello world")

编辑webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  // 主入口文件
  entry: __dirname + "/index.js",
  // 输出文件
  output: {
    filename: 'bundle.js',
    path: __dirname + "/dist"
  },
  // 开发模式
  mode: "development",
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    })
  ],
}

编辑package.json

"scripts": {
    "dev": "webpack --progress"
 },

执行 npm run dev,打开浏览器 http://localhost:8080,

image.png 我们的第一个程序,hello world 成功啦~

三. Loader

webpack一切皆模块,但它只能处理js和json文件。

1. 如果我们需要在js文件中使用es6语法,该如何操作呢?

这个时候,我们需要babel

安装
yarn add -D @babel/core@7.9.6 babel-loader@8.1.0 
在webpack中添加loader配置
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  // 主入口文件
  entry: __dirname + "/index.js",
  // 输出文件
  output: {
    filename: 'bundle.js',
    path: __dirname + "/dist"
  },
  // 开发模式
  mode: "development",
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    })
  ],
  // 添加loader
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader"
        },
        exclude: /node_modules/
      }
    ]
  }
}
测试
touch test.js

在test.js文件中,添加如下代码:

export function Hi() {
  return "hi es6";
}

在index.js中引用

import { Hi } from "./test";

let res = Hi();

console.log(res); // hi es6

到这里,我们可以愉快的使用es6 coding啦~

2. 如果我们需要添加css文件,该如何操作呢?

这个时候,我们需要css-loader, style-loader

安装
yarn add -D css-loader style-loader
修改webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  // 主入口文件
  entry: __dirname + "/index.js",
  // 输出文件
  output: {
    filename: 'bundle.js',
    path: __dirname + "/dist"
  },
  // 开发模式
  mode: "development",
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    })
  ],
  // 添加loader
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader"
        },
        exclude: /node_modules/
      },
      // 添加css-loader, style-loader
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
    ]
  }
}

注意:webpack执行style-loader, css-loader时, 从右往左执行,顺序不可颠倒

测试

修改index.js

import { Hi } from "./test";
// 引入css文件
import "./index.css";

let res = Hi();

console.log(res);

index.css

.root {
  width: 100%;
  height: 100%;
  background: blue;
}

这个时候,我们会看到页面变成了蓝色,样式问题搞定,可以愉快的编写css啦~

3. 如果我们需要添加.vue文件,该如何操作呢?

这个时候,我们需要尤大的vue-loader

安装
yarn add -D vue-loader@15.9.5 vue-template-compiler@2.6.12
yarn add vue@2.6.12
修改webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");

module.exports = {
  // 主入口文件
  entry: __dirname + "/index.js",
  // 输出文件
  output: {
    filename: 'bundle.js',
    path: __dirname + "/dist"
  },
  // 开发模式
  mode: "development",
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    // 添加vue loader 插件
    new VueLoaderPlugin(),
  ],
  // 添加loader
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader"
        },
        exclude: /node_modules/
      },
      // 添加css-loader, style-loader
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      // 添加.vue loader
      {
        test: /\.vue$/,
        loader: "vue-loader"
      },
    ]
  }
}
测试

修改index.js

// 引入css文件
import "./index.css";
import Vue from "vue";
// 引入vue文件
import HelloVue from "./hello.vue";

new Vue({
  render: h => h(HelloVue)
}).$mount('#root');

当前目录下:添加hello.vue文件


<template>
  <div>你好 vue</div>
</template>

<script>
export default {
  data() {
    return {
      
    }
  }  
}
</script>

<style scoped>

</style>

image.png

vue-loader配置成功,我们可以愉快的编写vue啦~

其实其他文件也类似,我们只需要使用对应的loader去解析对应的文件,就可以了。 loader的本质,将webpack不认识的文件,转化为webpack可识别的格式

四. Plugin

plugin 用于扩展 Webpack 功能,各种各样的 Plugin 几乎让 Webpack 可以做任何构建相关的事件。 plugin 的配置很简单,plugins 配置项接受一个数组,数组里每一项都是一个要使用的 plugin 的实例。

举个🌰: 我们在构建时,需要了解构建的进度,那么我们这个时候需要插件来解决。

安装
yarn add -D progress-bar-webpack-plugin@1.11.0
修改webpack.config.js配置
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
// 添加进度条插件
const ProgressBarPlugin = require("progress-bar-webpack-plugin");

module.exports = {
  // 主入口文件
  entry: __dirname + "/index.js",
  // 输出文件
  output: {
    filename: 'bundle.js',
    path: __dirname + "/dist"
  },
  // 开发模式
  mode: "development",
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html"
    }),
    // 添加vue loader 插件
    new VueLoaderPlugin(),

    // 使用进度条插件
    new ProgressBarPlugin()
  ],
  // 添加loader
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader"
        },
        exclude: /node_modules/
      },
      // 添加css-loader, style-loader
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      // 添加.vue loader
      {
        test: /\.vue$/,
        loader: "vue-loader"
      },
    ]
  }
}
测试

image.png

构建进度条插件添加成功~

使用 Plugin 的难点在于掌握 Plugin 本身提供的配置项,而不是如何在 Webpack 中接入 Plugin。

几乎所有 Webpack 无法直接实现的功能都能在社区找到开源的 Plugin 去解决。

到这里,我们已经入门了webpack的基本操作。码字不易,还请多多关注~😽