index.ts 1.4 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import fs from 'fs'
2
import path from 'path'
fxy060608's avatar
fxy060608 已提交
3
import { parse } from 'jsonc-parser'
fxy060608's avatar
fxy060608 已提交
4

5
import { Plugin, ViteDevServer } from 'vite'
fxy060608's avatar
fxy060608 已提交
6

fxy060608's avatar
fxy060608 已提交
7
import { initEnv } from './env'
8 9 10 11 12 13
import { createConfig } from './config'
import { createResolveId } from './resolveId'
import { createConfigResolved } from './configResolved'
import { createConfigureServer } from './configureServer'
export interface VitePluginUniOptions {
  inputDir?: string
fxy060608's avatar
fxy060608 已提交
14
}
15 16
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
  root: string
fxy060608's avatar
fxy060608 已提交
17
  base: string
18
  inputDir: string
fxy060608's avatar
fxy060608 已提交
19
  assetsDir: string
20
  devServer?: ViteDevServer
fxy060608's avatar
fxy060608 已提交
21
}
22

fxy060608's avatar
fxy060608 已提交
23
export * from './vue'
24

fxy060608's avatar
fxy060608 已提交
25 26 27 28 29 30 31
function resolveBase(inputDir: string) {
  const manifest = parse(
    fs.readFileSync(path.join(inputDir, 'manifest.json'), 'utf8')
  )
  return (manifest.h5 && manifest.h5.router && manifest.h5.router.base) || '/'
}

32 33 34
export default function uniPlugin(
  rawOptions: VitePluginUniOptions = {}
): Plugin {
fxy060608's avatar
fxy060608 已提交
35
  const inputDir = rawOptions.inputDir || path.resolve(process.cwd(), 'src')
36 37 38
  const options: VitePluginUniResolvedOptions = {
    ...rawOptions,
    root: process.cwd(),
fxy060608's avatar
fxy060608 已提交
39
    base: resolveBase(inputDir),
fxy060608's avatar
fxy060608 已提交
40
    assetsDir: 'assets',
fxy060608's avatar
fxy060608 已提交
41
    inputDir,
42
  }
fxy060608's avatar
fxy060608 已提交
43
  initEnv(options)
44 45
  return {
    name: 'vite:uni',
46 47 48 49
    config: createConfig(options),
    configResolved: createConfigResolved(options),
    configureServer: createConfigureServer(options),
    resolveId: createResolveId(options),
50 51
  }
}