Vue源码学习笔记-mustache模板引擎(三)-创建扫描类对模板字符串扫描

169 阅读1分钟

准备工作

1.Webpack安装,配置 2.创建UMD模块(兼容AMD和commonJS规范的同时,还兼容全局引用的方式) 3.创建scanner

Webpack 安装

npm install webpack@4.44.2 webpack-cli@3.3.12 webpack-dev-server@3.11.0

// 配置
const path = require("path");
module.exports = {
  mode: "development",
  entry: './src/index.js',
  output: {
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: path.join(__dirname, 'www'),
    compress: false,
    port: 8080,
    publicPath: '/xuni/'
  }
}

创建UMD模块

// 引入扫描类
import Scanner from './scaner'
// UMD对象
window.TpEngine = {
  render(tpStr, data) {
    console.log('render函数被调用,命令Scanner工作')
    // 扫描类
    const ScannerInit = new Scanner(tpStr)
    // 指针没移动到最后一位就循环
    while (ScannerInit.pos !== tpStr.length) {
      // 匹配头
      const word = ScannerInit.scanUtil('{{')
      console.log(word)
      // 跳过 {{
      ScannerInit.scan('{{')
      // 匹配尾巴
      words = ScannerInit.scanUtil('}}')
      console.log(words)
      // 跳过 }}
      ScannerInit.scan('}}')
    }
  }
}

创建扫描类对模板字符串进行扫描

// 创建扫描类
export default class Scanner {
  constructor(tpStr) {
    console.log('render函数里 调用Scanner')
    this.tpStr = tpStr
    // 建立指针
    this.pos = 0
    // 尾部字符串,默认为整个字符串
    this.tail = tpStr
  }
  scan(tag) {
    if (this.tail.indexOf(tag) === 0) {
      // tag 有多长,指针就往后移动几位
      this.pos += tag.length
      // tail1也要调整
      this.tail = this.tpStr.substring(this.pos)
    }
  }
  // 让指针扫描吗,直到内容结束,并返回之前查到的文字
  sacnUtil(stopTag) {
    // 记录指针原始位置
    const pos_backup = this.pos
    // 当尾巴的开头不是 stopTag的时候,就说明没有扫描到stopTag
    // 写 && 很有必要,防止越界 
    while (this.tail.indexOf(stopTag) !== 0 && !this.eos()) {
      this.pos++
      //
      console.log('pos--------------', this.pos)
      // 重新计算尾巴,从指针开始,到最后一位(第一个参数是启始,第二个是个数,如果省略了该参数)
      this.tail = this.tpStr.substr(this.pos)
    }
    // 返回位于 String 对象中指定位置的子字符串(两个指定下标之间的字符,如果省略该参数,那么返回的子串会一直到字符串的结尾)
    return this.tpStr.substring(pos_backup, this.pos)
  }
  // 指针防止越界
  eos() {
    return this.pos >= this.tpStr.length
  }
}