plugin.ts 1.5 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 33 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
import fs from 'fs'
import path from 'path'
import type { Plugin } from 'vite'
import type { RollupOptions } from 'rollup'
import {
  MP_PLUGIN_JSON_NAME,
  parseJson,
  removeExt,
  resolveMainPathOnce,
} from '@dcloudio/uni-cli-shared'
import { UniMiniProgramPluginOptions } from '../plugin'
import { createNonAppGenerateBundle } from './subpackage'
import { extend } from '@vue/shared'
import { notFound } from '../plugin/build'

export function uniMiniProgramPluginPlugin({
  style: { extname },
}: UniMiniProgramPluginOptions): Plugin {
  const entry = initPluginEntry()
  const rollupOptions: RollupOptions = {}
  if (entry) {
    rollupOptions.input = extend(
      {
        app: resolveMainPathOnce(process.env.UNI_INPUT_DIR),
      },
      entry
    )
  }
  return {
    name: 'vite:uni-mp-plugin',
    enforce: 'post',
    config() {
      return {
        build: {
          rollupOptions,
        },
      }
    },
    generateBundle: createNonAppGenerateBundle(extname),
  }
}

function initPluginEntry(): Record<string, string> | void {
  const pluginJsonFilename = path.resolve(
    process.env.UNI_INPUT_DIR,
    MP_PLUGIN_JSON_NAME
  )
  if (!fs.existsSync(pluginJsonFilename)) {
    notFound(pluginJsonFilename)
  }
  const pluginJson = parseJson(
    fs.readFileSync(pluginJsonFilename, 'utf8'),
    true
  )
  if (!pluginJson.main) {
    return
  }
  const mainFilename = path.resolve(process.env.UNI_INPUT_DIR, pluginJson.main)
  if (!fs.existsSync(mainFilename)) {
    notFound(mainFilename)
  }
  return {
    [removeExt(pluginJson.main)]: mainFilename,
  }
}