1. 第一步:准备阶段
  • 1 使用npm init -y 快速初始化package.json文件
  • 2 使用npm i webpack webpack-cli 安装webpack webpack4.0后需要依赖webpack-cli
  • 3 在根目录新建webpack配置文件webpack.config.js,它的作用就是告诉webpack干哪些活,当你运行webpack指令时,会加载里面的配置
  • 4 准备演示资源目录,src/index.js(随意写点内容,console.log('success');) ./src/index.html
第二步:编写webpack.config.js 入口
const {resolve} = require('path');
module.exports = {
   entry:'./src/index.js',
   output:{
     filename:'build.js',
     path:resolve(__dirname,'build')
   },
   mode:'development'
}

运行webpack 打包成功 可以看到多出一个build目录,里面有个build.js文件

你也可以在package.json中scripts对象里面做配置:
'build':'webpack'

你就可以使用npm run build 打包, 跟直接webpack运行打包一样,但是webpack打包是可以配置更多配置选项,此时写在package.json中才是正确的选则。

下面打包html
  • 1 npm i html-webpack-plugin -D 安装html插件
  • 2 在webpack.config.js中 使用html-webpack-plugin插件
const {resolve} = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
   entry:'./src/index.js',
   output:{
     filename:'build.js',
     path:resolve(__dirname,'build')
   },
   mode:'development',
   plugins:[
      new HtmlWebpackPlugin({
         template:'./src/index.html',
          // 压缩html代码
          minify: {
            // 移除空格
            collapseWhitespace: true,
            // 移除注释
            removeComments: true
      }
      })
   ]
}

html-webpack-plugin是html模板插件,就是一个类,使用时通过new创建实例,放在plugins数组里面,插件会有很多,所以plugins是数组,里面存放插件的实例, 好了,现在运行webpack 你会看到在打包后的build目录中多了一个index.html,而且自动引入了build.js,预览index.html,可以在控制台中看到控制台输出success

下面我们来看下 打包后的build.js 是什么样子的呢?

 (function(modules) { // webpackBootstrap
     // The module cache
     var installedModules = {};

     // The require function
     function __webpack_require__(moduleId) {

         // Check if module is in cache
         if(installedModules[moduleId]) {
             return installedModules[moduleId].exports;
         }
         // Create a new module (and put it into the cache)
         var module = installedModules[moduleId] = {
             i: moduleId,
             l: false,
             exports: {}
         };

         // Execute the module function
         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

         // Flag the module as loaded
         module.l = true;

         // Return the exports of the module
         return module.exports;
     }
     // Load entry module and return exports
     return __webpack_require__(__webpack_require__.s = "./src/index.js");
 })
 (
   {
    "./src/index.js":(function(module, exports) {
         eval("console.log('success');\n\n//# sourceURL=webpack:///./src/index.js?");
    })
  }
);

删除注释代码,和一些无用代码,我们整体看打包后的build.js 是一个自执行函数,实现了require 方法,自执行函数的参数是一个对象,这个对象的结构是文件的相对路径作为key,函数作为值,使用eval 执行js文件中的代码(字符串)

注意:
  • 1 webpack nodejs平台上运行 模块化默认采用commonjs。
  • 2 output 中的path一定要写绝对路径
  • 3 html-webpack-plugin 默认会创建一个空的HTML,自动引入打包输出的所有资源(JS/CSS)

带你入门前端
38 声望2 粉丝

通俗易懂,言简意赅授课