script.js 1.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
const path = require('path')
const babel = require('@babel/core')

const {
  hashify,
  removeExt,
  hasModule
} = require('@dcloudio/uni-cli-shared')

const {
  resolve,
  cacheCompilerOptions
} = require('./shared')

const babelPluginScopedComponent = require('./babel-plugin-scoped-component')

module.exports = function (content, map) {
  if (process.env.UNI_USING_COMPONENTS) {
    if (process.env.UNI_PLATFORM === 'app-plus') {
      return require('./script-new').call(this, content, map)
    }
    return require('./script-new').call(this, content)
  }

  this.cacheable && this.cacheable()
  // 单页面 解析 component 依赖
  const plugins = []
  if (hasModule('@babel/plugin-syntax-typescript')) {
    plugins.push('@babel/plugin-syntax-typescript')
    plugins.push([
      '@babel/plugin-proposal-decorators',
      {
fxy060608's avatar
fxy060608 已提交
33
        legacy: true
fxy060608's avatar
fxy060608 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
      }
    ])
  }
  plugins.push(babelPluginScopedComponent)
  const ast = babel.transform(content, {
    configFile: false,
    plugins
  })

  const components = ast.metadata.components || {}

  const imports = {}

  const callback = this.async()

  Promise.all(Object.keys(components).map(name => {
    return resolve.call(this, components[name]).then(resolved => {
      resolved = path.relative(process.env.UNI_INPUT_DIR, resolved)
      const hashed = hashify(resolved)
      imports[name] = {
        name: hashed,
        src: removeExt(resolved)
      }
    })
  })).then(() => {
    const realResourcePath = path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)
    const compilerOptions = {
      name: hashify(realResourcePath),
      imports
    }
    cacheCompilerOptions(realResourcePath, compilerOptions)
    callback(null, content, map)
  }, err => {
    callback(err, content, map)
  })
}