美文网首页
编写 webpack loader

编写 webpack loader

作者: 梦想成真213 | 来源:发表于2021-05-14 15:29 被阅读0次

    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/

    相关文章

      网友评论

          本文标题:编写 webpack loader

          本文链接:https://www.haomeiwen.com/subject/ggxvrltx.html