index.ts 1.6 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

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

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

fxy060608's avatar
fxy060608 已提交
25
export * from './vue'
26

fxy060608's avatar
fxy060608 已提交
27 28 29 30 31 32 33
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) || '/'
}

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