编写 webpack loader

loader

loader 用于对模块的源代码进行转换。loader 可以使你在 import 或 "load(加载)" 模块时预处理文件。因此,loader 类似于其他构建工具中“任务(task)”,并提供了处理前端构建步骤的得力方式。loader 可以将文件从不同的语言(如 TypeScript)转换为 JavaScript 或将内联图像转换为 data URL。loader 甚至允许你直接在 JavaScript 模块中 import CSS 文件!

loader 特性

  • loader 支持链式调用。链中的每个 loader 会将转换应用在已处理过的资源上。一组链式的 loader 将按照相反的顺序执行。链中的第一个 loader 将其结果(也就是应用过转换后的资源)传递给下一个 loader,依此类推。最后,链中的最后一个 loader,返回 webpack 所期望的 JavaScript。
  • loader 可以是同步的,也可以是异步的。
  • loader 运行在 Node.js 中,并且能够执行任何操作。
  • loader 可以通过 options 对象配置。
  • 除了常见的通过 package.jsonmain 来将一个 npm 模块导出为 loader,还可以在 module.rules 中使用 loader 字段直接引用一个模块。
  • 插件(plugin)可以为 loader 带来更多特性。
  • loader 能够产生额外的任意文件。

可以通过 loader 的预处理函数,为 JavaScript 生态系统提供更多能力。用户现在可以更加灵活地引入细粒度逻辑,例如:压缩、打包、语言翻译和 更多其他特性

解析 loader

loader 遵循标准 模块解析 规则。多数情况下,loader 将从 模块路径 加载(通常是从 npm install, node_modules 进行加载)。

我们预期 loader 模块导出为一个函数,并且编写为 Node.js 兼容的 JavaScript。通常使用 npm 进行管理 loader,但是也可以将应用程序中的文件作为自定义 loader。按照约定,loader 通常被命名为 xxx-loader(例如 json-loader)。

编写loader

loader 就是一个函数,输入源代码,返回新代码。
下面来实现一个 加载原始文件内内容的 loader:

function rawLoader (source) {
  return source
}

module.exports = rawLoader

没错,这样就实现了一个返回原始文件内容的 loader,简单么:)。npm 上有这样一个loader (raw-loader),在 webpack 5 上已经被废弃,建议迁移至asset modules中。

实现 px2vw-loader

下面实现 px2vw-loader ,这个 loader 是找到 css 代码中的 px 单位,将所有的 px 转化为 vw,使网页变成响应式的。
vw 参照的是 viewport 适口,1vw 就表示 viewport 的百分之一,这样把网页按照百分比切割,很好的实现响应式,目前浏览器的支持也很好,主流的互联网公司现在都采用的是 vw 实现响应式。

根据我们的设计稿,通常是 iphone 6 的设计稿,它的适口宽度是 375px,转换成 vw 就是 375px 对应 100vw,所以 1vw 就代表 3.75px ,下面就来实战演示一下。

px2rem-loader

现在开始搭建一个项目,不使用脚手架。
安装 npm 包:

npm init
npm install webpack webpack-cli html-webpack-plugin style-loader css-loader amfe-flexible px2rem-loader -D

第三方包 px2rem-loader,会把样式中的px 变成 rem的单位。

  • webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use:[
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
          },
          {
            loader: 'px2rem-loader',
            options: {
              remUni: 75,
              remPrecision: 8
            }
          }
        ]
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
}
  • index.js
    import './index.css'
  • index.css
#root {
  width: 375px;
  height: 200px;
  background-color: red;
}
  • package.json
"scripts": {
    "build": "webpack"
  },

执行npm run build,打出来的样式文件会变成 rem 的单位:

\"#root {\\n  width: 5rem;\\n  height: 2.66666667rem;\\n  background-color: red;\\n}\", \"\"]);\n// Exports\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);\n\n\n//# sourceURL=webpack://webpack-loader/./src/index.css?./node_modules/css-loader/dist/cjs.js!./node_modules/px2rem-loader/index.js??ruleSet%5B1%5D.rules%5B0%5D.use%5B2%5D");

实现 px2vw-loader

在 webapck 配置文件同级建一个 loader 目录,在 loader 目录下新建一个 px2rem-loader.js 文件,使用自定义的 px2vw-loader,配置 webpack 中自定义 loader,resolveLoader用来解析目录下的 loader,alias是 loader 的别名,在规则解析的时候用到,或者直接引入loader的本地路径path.resolve(__dirname, 'loaders/px2vw-loader.js')

// webpack.config.js
...
output: {},
resolveLoader: {
    alias: {
      "px2vw-loader": path.resolve('./loaders/px2vw-loader.js')
    },
    modules: [path.resolve('./loaders'), 'node_modules']
  },
module: {
    rules: [
      {
        test: /\.css$/,
        use:[
          'style-loader',
          'css-loader',
          {
            loader: 'px2vw-loader',
            options: {
              unit: 375, // 设计稿的宽度
              decimal: 4, // 小数点个数
              excludes: /exclude\.css/, // 不解析哪些 css 文件
            }
          }
        ]
      },
    ]
  },
...

需要用到两个第三方库 css loader-utilscss.parse(source)将 css 代码解析为css ast 语法树,css.stringify(astObj)将解析之后的语法树再生成css代码。
loader-utils用来解析 loader 的 options 的配置项。

实现这个 loader 的三个步骤:

  • parse(解析):解析源代码为 ast,抽象语法树
  • transform(转换):对抽象语法树进行转换
  • generator(生成):将转换后的 ast 生成新的代码
    例如:
const cssText = `#root {
  width: 375px;
  height: 200px;
  background-color: red;
}`
const astObj = css.parse(cssText)
/**
 * css 文件解析出来的内容
 * {
  type: 'stylesheet',
  stylesheet: { source: undefined, rules: [ [Object] ], parsingErrors: [] }
  }
  样式相关的内容在 stylesheet.rules 中
  [
  {
    "type": "rule",
    "selectors": [
      "#root"
    ],
    "declarations": [
      {
        "type": "declaration",
        "property": "width",
        "value": "375px",
        "position": {
          "start": {
            "line": 2,
            "column": 3
          },
          "end": {
            "line": 2,
            "column": 15
          }
        }
      },
      {
        "type": "declaration",
        "property": "height",
        "value": "200px",
        "position": {
          "start": {
            "line": 3,
            "column": 3
          },
          "end": {
            "line": 3,
            "column": 16
          }
        }
      },
      {
        "type": "declaration",
        "property": "background-color",
        "value": "red",
        "position": {
          "start": {
            "line": 4,
            "column": 3
          },
          "end": {
            "line": 4,
            "column": 24
          }
        }
      }
    ],
    "position": {
      "start": {
        "line": 1,
        "column": 1
      },
      "end": {
        "line": 5,
        "column": 2
      }
    }
  }
]
 */

可以看到所有的规则都在stylesheet.rules 中,找到规则中 value 是px单位的,然后转换成 vw,即可。
下面是代码实现:

// loaders/px2vw-loader.js
const css = require('css') // 解析css 文件为 ast
const loaderUtils = require('loader-utils') // 解析传入 loader 的 options 值
const pxReg = /(\d+(\.\d+)?)px/ // px 的正则

function px2vwLoader(source) {
  const options = loaderUtils.getOptions(source)
  if (options.excludes && options.excludes.exec(this.resource)) {
    console.log('resource', this.resource)
    return source
  }
  
  function generateVw(source) {
    const cssObj = css.parse(source)

    function parseRules(rules) {
      for(let i = 0; i < rules.length; i++) {
        const rule = rules[i]
        const declarations = rule.declarations

        for(let j = 0; j < declarations.length; j++) {
          const declaration = declarations[j]
          if (declaration.type === 'declaration' && pxReg.test(declaration.value)) {
            declaration.value = _getVw(declaration.value, options)
          }
        } 
      }
    }

    parseRules(cssObj.stylesheet.rules) 
    return css.stringify(cssObj)
  }

  function _getVw(pxValue, options) {
    const number = pxReg.exec(pxValue)[1] // 250px
    // 假设设计稿宽度是 375
    const vwNumber = (number / ((options.unit) || 375)) * 100
    console.log('vwNumber', vwNumber)
    return `${vwNumber}vw`
  }
  
  return generateVw(source)
}

module.exports = px2vwLoader

使用 loader,打包可以看到生成的代码 px 变成了 vw:


基本功能实现了,现在优化一下代码,让 loader 的实现看起来更简洁明了。
新建一个px2vw.js,将 loader 中的代码拆一拆:

  • loaders/px2vw.js
// loaders/px2vw.js
const css = require('css')
const pxReg = /(\d+(\.\d+)?)px/ // px 的正则

class Px2vw {
  constructor(config) {
    this.config = config
  }

  generateVw(source) {
    const cssObj = css.parse(source)
    const rules = cssObj.stylesheet.rules

    for(let i = 0; i < rules.length; i++) {
      const rule = rules[i]
      const declarations = rule.declarations

      for(let j = 0; j < declarations.length; j++) {
        const declaration = declarations[j]
        if (declaration.type === 'declaration' && pxReg.test(declaration.value)) {
          declaration.value = this._getVw(declaration.value, this.config)
        }
      } 
    }

    return css.stringify(cssObj)    
  }

  _getVw(pxValue, options) {
    const number = pxReg.exec(pxValue)[1] // 250px -> 250
    const unit = options.unit || 375 // 不传默认是375
    const decimal = options.decimal || 8 // 保留几位小数 默认8位
    let newNumber = ((parseFloat(number) / unit) * 100)
    let vwText = newNumber.toFixed(decimal)
    return `${vwText}vw`
  }
}

module.exports = Px2vw
  • loaders/px2vw-loader.js
// loaders/px2vw-loader.js
const loaderUtils = require('loader-utils') // 解析传入 loader 的 options 值
const Px2vw = require('./px2vw')

function px2vwLoader(source) {
  const options = loaderUtils.getOptions(this)
  console.log('options', options)
  if (options.excludes && options.excludes.exec(this.resource)) {
    console.log('resource', this.resource)
    return source
  }
  const px2vwInstance = new Px2vw(options)
  const targeSource = px2vwInstance.generateVw(source)
  return targeSource
}

module.exports = px2vwLoader

看下打包出来的代码:.container {\\n width: 100px;\\n height: 20px;\\n}
#root {\\n width: 100.0000vw;\\n height: 53.3333vw;\\n background-color: red;\\n},被排除的 css 文件是没有被转化的,且按照 375 的设计稿进行了 vw 的转换,转换后的数字保留4位小数。

参考:
https://webpack.docschina.org/concepts/loaders/#root
https://webpack.docschina.org/loaders/
https://webpack.docschina.org/concepts/module-resolution/
https://webpack.docschina.org/contribute/writing-a-loader/
https://webpack.docschina.org/guides/asset-modules/

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容