index.js 7.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10
const path = require('path')

const parser = require('@babel/parser')

const {
  parseComponent,
  compile,
  compileToFunctions,
  ssrCompile,
  ssrCompileToFunctions
fxy060608's avatar
fxy060608 已提交
11
} = require('../../vue-cli-plugin-uni/packages/vue-template-compiler')
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18 19 20

const platforms = require('./platforms')
const traverseScript = require('./script/traverse')
const generateScript = require('./script/generate')
const traverseTemplate = require('./template/traverse')
const generateTemplate = require('./template/generate')

const compilerModule = require('./module')

fxy060608's avatar
fxy060608 已提交
21 22
const compilerAlipayModule = require('./module-alipay')

fxy060608's avatar
fxy060608 已提交
23 24
const generateCodeFrame = require('./codeframe')

fxy060608's avatar
fxy060608 已提交
25
const {
fxy060608's avatar
fxy060608 已提交
26
  isComponent,
fxy060608's avatar
fxy060608 已提交
27
  isUnaryTag
fxy060608's avatar
fxy060608 已提交
28 29
} = require('./util')

fxy060608's avatar
fxy060608 已提交
30 31 32 33
const {
  module: autoComponentsModule,
  compileTemplate
} = require('./auto-components')
fxy060608's avatar
fxy060608 已提交
34

fxy060608's avatar
fxy060608 已提交
35
module.exports = {
fxy060608's avatar
fxy060608 已提交
36
  compile (source, options = {}) {
fxy060608's avatar
fxy060608 已提交
37 38 39 40 41
    (options.modules || (options.modules = [])).push(autoComponentsModule)
    options.isUnaryTag = isUnaryTag
    // 将 autoComponents 挂在 isUnaryTag 上边
    options.isUnaryTag.autoComponents = new Set()

fxy060608's avatar
fxy060608 已提交
42
    options.preserveWhitespace = false
fxy060608's avatar
init v3  
fxy060608 已提交
43 44
    if (options.service) {
      (options.modules || (options.modules = [])).push(require('./app/service'))
fxy060608's avatar
fxy060608 已提交
45
      options.optimize = false // 启用 staticRenderFns
fxy060608's avatar
init v3  
fxy060608 已提交
46 47
      // domProps => attrs
      options.mustUseProp = () => false
fxy060608's avatar
fxy060608 已提交
48 49 50
      options.isReservedTag = (tagName) => !isComponent(tagName) // 非组件均为内置
      options.getTagNamespace = () => false

51
      try {
fxy060608's avatar
fxy060608 已提交
52
        return compileTemplate(source, options, compile)
53
      } catch (e) {
fxy060608's avatar
fxy060608 已提交
54 55
        console.error(source)
        throw e
56
      }
fxy060608's avatar
init v3  
fxy060608 已提交
57 58
    } else if (options.view) {
      (options.modules || (options.modules = [])).push(require('./app/view'))
fxy060608's avatar
fxy060608 已提交
59
      options.optimize = false // 暂不启用 staticRenderFns
fxy060608's avatar
fxy060608 已提交
60
      options.isUnaryTag = isUnaryTag
fxy060608's avatar
fxy060608 已提交
61
      options.isReservedTag = (tagName) => false // 均为组件
62
      try {
fxy060608's avatar
fxy060608 已提交
63
        return compileTemplate(source, options, compile)
64
      } catch (e) {
fxy060608's avatar
fxy060608 已提交
65 66
        console.error(source)
        throw e
67
      }
fxy060608's avatar
init v3  
fxy060608 已提交
68 69
    }

fxy060608's avatar
fxy060608 已提交
70
    if (!options.mp) { // h5
fxy060608's avatar
fxy060608 已提交
71
      return compileTemplate(source, options, compile)
fxy060608's avatar
fxy060608 已提交
72 73 74 75
    }

    (options.modules || (options.modules = [])).push(compilerModule)

fxy060608's avatar
fxy060608 已提交
76 77 78 79
    if (options.mp.platform === 'mp-alipay') {
      options.modules.push(compilerAlipayModule)
    }

fxy060608's avatar
fxy060608 已提交
80
    const res = compileTemplate(source, Object.assign(options, {
fxy060608's avatar
fxy060608 已提交
81
      optimize: false
fxy060608's avatar
fxy060608 已提交
82
    }), compile)
fxy060608's avatar
fxy060608 已提交
83 84 85 86 87 88 89 90

    options.mp.platform = platforms[options.mp.platform]

    options.mp.scopeId = options.scopeId

    options.mp.resourcePath = options.resourcePath

    options.mp.globalUsingComponents = options.globalUsingComponents || Object.create(null)
91 92

    options.mp.filterModules = Object.keys(options.filterModules || {})
fxy060608's avatar
fxy060608 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106

    // (可用的原生微信小程序组件,global+scoped)
    options.mp.wxComponents = options.wxComponents || Object.create(null)

    const state = {
      ast: {},
      script: '',
      template: '',
      errors: new Set(),
      tips: new Set(),
      options: options.mp
    }
    // console.log(`function render(){${res.render}}`)
    const ast = parser.parse(`function render(){${res.render}}`)
107 108 109 110 111 112 113 114 115 116 117 118
    let template = ''

    try {
      res.render = generateScript(traverseScript(ast, state), state)
      template = generateTemplate(traverseTemplate(ast, state), state)
    } catch (e) {
      console.error(e)
      throw new Error('Compile failed at ' + options.resourcePath.replace(
        path.extname(options.resourcePath),
        '.vue'
      ))
    }
fxy060608's avatar
fxy060608 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    res.specialMethods = state.options.specialMethods || new Set()
    delete state.options.specialMethods

    res.files = state.files || {}
    delete state.files

    // resolve scoped slots
    res.generic = state.generic || []
    delete state.generic

    // define scoped slots
    res.componentGenerics = state.componentGenerics || {}
    delete state.componentGenerics

    state.errors.forEach(msg => {
      res.errors.push({
        msg
      })
    })

    const resourcePath = options.resourcePath.replace(path.extname(options.resourcePath), '')

    state.tips.forEach(msg => {
      console.log(`提示:${msg}
at ${resourcePath}.vue:1`)
    })

    /**
148 149 150 151 152 153
     * TODO
     * 方案0.最佳方案是在 loader 中直接 emitFile,但目前 vue template-loader 不好介入,自定义的 compiler 结果又无法顺利返回给 loader
     * 方案1.通过 loader 传递 emitFile 来提交生成 wxml,需要一个 template loader 来给自定义 compier 增加 emitFile
     * 方案2.缓存 wxml 内容,由 plugin 生成 assets 来提交生成 wxml
     * ...暂时使用方案1
     */
fxy060608's avatar
fxy060608 已提交
154
    if (options.emitFile) {
fxy060608's avatar
fxy060608 已提交
155 156 157 158 159 160 161 162 163 164 165
      // cache
      if (process.env.UNI_USING_CACHE) {
        const oldEmitFile = options.emitFile
        process.UNI_CACHE_TEMPLATES = {}
        options.emitFile = function emitFile (name, content) {
          const absolutePath = path.resolve(process.env.UNI_OUTPUT_DIR, name)
          process.UNI_CACHE_TEMPLATES[absolutePath] = content
          oldEmitFile(name, content)
        }
      }

fxy060608's avatar
fxy060608 已提交
166 167 168
      if (options.updateSpecialMethods) {
        options.updateSpecialMethods(resourcePath, [...res.specialMethods])
      }
169 170
      const filterTemplate = []
      options.mp.filterModules.forEach(name => {
fxy060608's avatar
fxy060608 已提交
171 172 173 174 175 176 177
        const filterModule = options.filterModules[name]
        if (filterModule.type !== 'renderjs' && filterModule.attrs.lang !== 'renderjs') {
          filterTemplate.push(
            options.mp.platform.createFilterTag(
              options.filterTagName,
              options.filterModules[name]
            )
fxy060608's avatar
fxy060608 已提交
178
          )
fxy060608's avatar
fxy060608 已提交
179
        }
180
      })
fxy060608's avatar
fxy060608 已提交
181

fxy060608's avatar
fxy060608 已提交
182 183 184 185
      if (filterTemplate.length) {
        template = filterTemplate.join('\n') + '\n' + template
      }

fxy060608's avatar
fxy060608 已提交
186 187
      if (
        process.UNI_ENTRY[resourcePath] &&
188 189
        process.env.UNI_PLATFORM !== 'app-plus' &&
        process.env.UNI_PLATFORM !== 'h5'
fxy060608's avatar
fxy060608 已提交
190 191 192 193 194 195 196 197 198
      ) {
        // 检查是否启用 shadow
        let colorType = false
        const pageJsonStr = options.getJsonFile(resourcePath)
        if (pageJsonStr) {
          try {
            const windowJson = JSON.parse(pageJsonStr)
            if (process.env.UNI_PLATFORM === 'mp-alipay') {
              colorType = windowJson.allowsBounceVertical === 'NO' &&
199 200
                windowJson.navigationBarShadow &&
                windowJson.navigationBarShadow.colorType
fxy060608's avatar
fxy060608 已提交
201 202
            } else {
              colorType = windowJson.disableScroll &&
203 204
                windowJson.navigationBarShadow &&
                windowJson.navigationBarShadow.colorType
fxy060608's avatar
fxy060608 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            }
          } catch (e) {}
        }
        if (colorType) {
          template = options.getShadowTemplate(colorType) + template
        }
      }

      options.emitFile(options.resourcePath, template)
      if (res.files) {
        Object.keys(res.files).forEach(name => {
          options.emitFile(name, res.files[name])
        })
      }

      if (state.options.usingGlobalComponents) {
        options.updateUsingGlobalComponents(
          resourcePath,
          state.options.usingGlobalComponents
        )
      }

      if (
        res.generic &&
229 230
        res.generic.length &&
        options.updateGenericComponents
fxy060608's avatar
fxy060608 已提交
231 232 233 234 235 236 237 238
      ) {
        options.updateGenericComponents(
          resourcePath,
          res.generic
        )
      }
      if (
        res.componentGenerics &&
239 240
        Object.keys(res.componentGenerics).length &&
        options.updateComponentGenerics
fxy060608's avatar
fxy060608 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
      ) {
        options.updateComponentGenerics(
          resourcePath,
          res.componentGenerics
        )
      }
    } else {
      res.template = template
    }
    return res
  },
  parseComponent,
  compileToFunctions,
  ssrCompile,
  ssrCompileToFunctions,
  generateCodeFrame
}