esbuild.ts 5.2 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import type { Plugin, ResolvedConfig } from 'vite'
fxy060608's avatar
fxy060608 已提交
2 3
import type { BuildOptions, PluginBuild } from 'esbuild'

fxy060608's avatar
fxy060608 已提交
4 5
import path from 'path'
import fs from 'fs-extra'
fxy060608's avatar
fxy060608 已提交
6
import debug from 'debug'
fxy060608's avatar
fxy060608 已提交
7

fxy060608's avatar
fxy060608 已提交
8 9
import {
  APP_CONFIG_SERVICE,
fxy060608's avatar
fxy060608 已提交
10
  hash,
fxy060608's avatar
fxy060608 已提交
11 12 13
  removeExt,
  transformWithEsbuild,
} from '@dcloudio/uni-cli-shared'
fxy060608's avatar
fxy060608 已提交
14

fxy060608's avatar
fxy060608 已提交
15
import { nvueOutDir } from '../../utils'
fxy060608's avatar
fxy060608 已提交
16
import { esbuildGlobals } from '../utils'
fxy060608's avatar
fxy060608 已提交
17
import { APP_CSS_JS } from './appCss'
fxy060608's avatar
fxy060608 已提交
18

fxy060608's avatar
fxy060608 已提交
19
const debugEsbuild = debug('uni:app-nvue-esbuild')
fxy060608's avatar
fxy060608 已提交
20

fxy060608's avatar
fxy060608 已提交
21 22
const emittedHashMap = new WeakMap<ResolvedConfig, Map<string, string>>()

fxy060608's avatar
fxy060608 已提交
23
export function uniEsbuildPlugin({
fxy060608's avatar
fxy060608 已提交
24
  appService,
fxy060608's avatar
fxy060608 已提交
25 26
}: {
  renderer?: 'native'
fxy060608's avatar
fxy060608 已提交
27
  appService: boolean
fxy060608's avatar
fxy060608 已提交
28
}): Plugin {
fxy060608's avatar
fxy060608 已提交
29
  let resolvedConfig: ResolvedConfig
fxy060608's avatar
fxy060608 已提交
30 31
  let buildOptions: BuildOptions
  const outputDir = process.env.UNI_OUTPUT_DIR
fxy060608's avatar
fxy060608 已提交
32
  let isFirst = true
fxy060608's avatar
fxy060608 已提交
33 34 35
  return {
    name: 'uni:app-nvue-esbuild',
    enforce: 'post',
fxy060608's avatar
fxy060608 已提交
36 37 38
    configResolved(config) {
      buildOptions = {
        format: 'iife',
fxy060608's avatar
fxy060608 已提交
39
        target: 'es6',
fxy060608's avatar
fxy060608 已提交
40
        minify: config.build.minify ? true : false,
fxy060608's avatar
fxy060608 已提交
41 42 43
        banner: {
          js: `"use weex:vue";`,
        },
fxy060608's avatar
fxy060608 已提交
44 45
        bundle: true,
        write: false,
fxy060608's avatar
fxy060608 已提交
46
        plugins: [esbuildGlobalPlugin(esbuildGlobals(appService))],
fxy060608's avatar
fxy060608 已提交
47
      }
fxy060608's avatar
fxy060608 已提交
48 49
      resolvedConfig = config
      emittedHashMap.set(resolvedConfig, new Map<string, string>())
fxy060608's avatar
fxy060608 已提交
50
    },
fxy060608's avatar
fxy060608 已提交
51 52 53 54 55 56 57 58 59 60 61 62
    async writeBundle(_, bundle) {
      const entryPoints: string[] = []
      Object.keys(bundle).forEach((name) => {
        const chunk = bundle[name]
        if (
          chunk.type === 'chunk' &&
          chunk.facadeModuleId &&
          chunk.facadeModuleId.endsWith('.nvue')
        ) {
          entryPoints.push(name)
        }
      })
fxy060608's avatar
fxy060608 已提交
63 64 65
      if (!entryPoints.length) {
        return
      }
fxy060608's avatar
fxy060608 已提交
66 67 68 69 70
      const emittedHash = emittedHashMap.get(resolvedConfig)!
      const changedFiles: string[] = []
      if (buildAppCss()) {
        changedFiles.push(APP_CONFIG_SERVICE)
      }
fxy060608's avatar
fxy060608 已提交
71
      debugEsbuild('start', entryPoints.length, entryPoints)
fxy060608's avatar
fxy060608 已提交
72
      for (const filename of entryPoints) {
fxy060608's avatar
fxy060608 已提交
73
        await buildNVuePage(filename, buildOptions).then((code) => {
fxy060608's avatar
fxy060608 已提交
74 75 76 77 78 79
          const outputFileHash = hash(code)
          if (emittedHash.get(filename) !== outputFileHash) {
            changedFiles.push(filename)
            emittedHash.set(filename, outputFileHash)
            return fs.outputFile(path.resolve(outputDir, filename), code)
          }
fxy060608's avatar
fxy060608 已提交
80
        })
fxy060608's avatar
fxy060608 已提交
81
      }
fxy060608's avatar
fxy060608 已提交
82 83 84 85 86 87 88
      if (!isFirst && changedFiles.length) {
        process.env[
          changedFiles.includes(APP_CONFIG_SERVICE)
            ? 'UNI_APP_CHANGED_FILES'
            : 'UNI_APP_CHANGED_PAGES'
        ] = JSON.stringify(changedFiles)
      }
fxy060608's avatar
fxy060608 已提交
89
      debugEsbuild('end')
fxy060608's avatar
fxy060608 已提交
90
      isFirst = false
fxy060608's avatar
fxy060608 已提交
91 92 93 94
    },
  }
}

fxy060608's avatar
fxy060608 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
/**
 * 将 nvue 全局 css 样式注入 app-config-service.js
 * @returns
 */
function buildAppCss() {
  const appCssJsFilename = path.join(nvueOutDir(), APP_CSS_JS)
  if (!fs.existsSync(appCssJsFilename)) {
    return
  }
  const appCssJsCode = fs.readFileSync(appCssJsFilename, 'utf8')
  const appCssJsFn = new Function('exports', appCssJsCode)
  const exports = { styles: [] }
  appCssJsFn(exports)
  const appCssJsonCode = JSON.stringify(exports.styles)
  if (process.env.UNI_NVUE_APP_STYLES === appCssJsonCode) {
    return
  }
  process.env.UNI_NVUE_APP_STYLES = appCssJsonCode
fxy060608's avatar
fxy060608 已提交
113 114 115 116 117 118 119 120
  // 首次 build 时,可能还没生成 app-config-service 的文件,故仅写入环境变量
  const appConfigServiceFilename = path.join(
    process.env.UNI_OUTPUT_DIR,
    APP_CONFIG_SERVICE
  )
  if (!fs.existsSync(appConfigServiceFilename)) {
    return
  }
fxy060608's avatar
fxy060608 已提交
121 122 123 124 125
  const appConfigServiceCode = fs.readFileSync(appConfigServiceFilename, 'utf8')
  fs.writeFileSync(
    appConfigServiceFilename,
    wrapperNVueAppStyles(appConfigServiceCode)
  )
fxy060608's avatar
fxy060608 已提交
126
  return true
fxy060608's avatar
fxy060608 已提交
127 128 129
}

function buildNVuePage(filename: string, options: BuildOptions) {
fxy060608's avatar
fxy060608 已提交
130
  return transformWithEsbuild(
fxy060608's avatar
fxy060608 已提交
131
    `import App from './${filename}'
fxy060608's avatar
fxy060608 已提交
132
const webview = plus.webview.currentWebview()
fxy060608's avatar
fxy060608 已提交
133 134 135 136 137 138 139 140 141 142
if(webview){
  const __pageId = parseInt(webview.id)
  const __pagePath = '${removeExt(filename)}'
  let __pageQuery = {}
  try{ __pageQuery = JSON.parse(webview.__query__) }catch(e){}
  App.mpType = 'page'
  const app = Vue.createPageApp(App,{$store:getApp({allowDefault:true}).$store,__pageId,__pagePath,__pageQuery})
  app.provide('__globalStyles', Vue.useCssStyles([...__uniConfig.styles, ...(App.styles||[])]))
  app.mount('#root')
}`,
fxy060608's avatar
fxy060608 已提交
143
    path.join(nvueOutDir(), 'main.js'),
fxy060608's avatar
fxy060608 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    options
  ).then((res) => {
    if (res.outputFiles) {
      return res.outputFiles[0].text
    }
    return ''
  })
}

function esbuildGlobalPlugin(options: Record<string, string>) {
  const keys = Object.keys(options)
  return {
    name: 'global',
    setup(build: PluginBuild) {
      keys.forEach((key) => {
        const namespace = key + '-ns'
        build.onResolve({ filter: new RegExp('^' + key + '$') }, ({ path }) => {
          return {
            path,
            namespace,
          }
        })
        build.onLoad({ filter: /.*/, namespace }, () => ({
          contents: `module.exports = ${options[key]}`,
          loader: 'js',
        }))
fxy060608's avatar
fxy060608 已提交
170 171 172 173
      })
    },
  }
}
fxy060608's avatar
fxy060608 已提交
174 175 176 177 178 179 180

export function wrapperNVueAppStyles(code: string) {
  return code.replace(
    /__uniConfig.styles=(.*);\/\/styles/,
    `__uniConfig.styles=${process.env.UNI_NVUE_APP_STYLES || '[]'};//styles`
  )
}