build.ts 3.9 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import fs from 'fs'
fxy060608's avatar
fxy060608 已提交
2
import path from 'path'
fxy060608's avatar
fxy060608 已提交
3
import debug from 'debug'
fxy060608's avatar
fxy060608 已提交
4 5
import { UserConfig } from 'vite'

fxy060608's avatar
fxy060608 已提交
6
import {
fxy060608's avatar
fxy060608 已提交
7
  emptyDir,
fxy060608's avatar
fxy060608 已提交
8
  EXTNAME_JS_RE,
fxy060608's avatar
fxy060608 已提交
9 10
  isCSSRequest,
  normalizePath,
fxy060608's avatar
fxy060608 已提交
11 12
  hasJsonFile,
  removeExt,
fxy060608's avatar
fxy060608 已提交
13 14 15 16 17 18 19 20
  resolveMainPathOnce,
} from '@dcloudio/uni-cli-shared'
import { GetManualChunk, GetModuleInfo } from 'rollup'
import {
  isUniComponentUrl,
  isUniPageUrl,
  parseVirtualComponentPath,
  parseVirtualPagePath,
fxy060608's avatar
fxy060608 已提交
21
} from '../plugins/entry'
fxy060608's avatar
fxy060608 已提交
22

fxy060608's avatar
fxy060608 已提交
23 24
const debugChunk = debug('vite:uni:chunk')

fxy060608's avatar
fxy060608 已提交
25
export function buildOptions(): UserConfig['build'] {
fxy060608's avatar
fxy060608 已提交
26
  const inputDir = process.env.UNI_INPUT_DIR
fxy060608's avatar
fxy060608 已提交
27 28 29 30 31
  const outputDir = process.env.UNI_OUTPUT_DIR
  // 开始编译时,清空输出目录
  if (fs.existsSync(outputDir)) {
    emptyDir(outputDir)
  }
fxy060608's avatar
fxy060608 已提交
32 33
  return {
    // sourcemap: 'inline', // TODO
fxy060608's avatar
fxy060608 已提交
34
    target: ['chrome53'],
fxy060608's avatar
fxy060608 已提交
35
    emptyOutDir: false, // 不清空输出目录,否则会影响自定义的一些文件输出,比如wxml
fxy060608's avatar
fxy060608 已提交
36
    assetsInlineLimit: 40 * 1024, // 40kb
fxy060608's avatar
fxy060608 已提交
37 38 39 40
    lib: {
      entry: resolveMainPathOnce(inputDir),
      formats: ['cjs'],
    },
fxy060608's avatar
fxy060608 已提交
41 42
    rollupOptions: {
      output: {
fxy060608's avatar
fxy060608 已提交
43 44
        entryFileNames: 'app.js',
        manualChunks: createMoveToVendorChunkFn(),
fxy060608's avatar
fxy060608 已提交
45 46
        chunkFileNames(chunk) {
          if (chunk.isDynamicEntry && chunk.facadeModuleId) {
fxy060608's avatar
fxy060608 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59
            let id = chunk.facadeModuleId
            if (isUniPageUrl(id)) {
              id = path.resolve(
                process.env.UNI_INPUT_DIR,
                parseVirtualPagePath(id)
              )
            } else if (isUniComponentUrl(id)) {
              id = path.resolve(
                process.env.UNI_INPUT_DIR,
                parseVirtualComponentPath(id)
              )
            }
            const filepath = path.relative(inputDir, id)
fxy060608's avatar
fxy060608 已提交
60 61 62 63 64 65 66 67 68 69 70
            return normalizePath(
              filepath.replace(path.extname(filepath), '.js')
            )
          }
          return '[name].js'
        },
        assetFileNames: '[name][extname]',
      },
    },
  }
}
fxy060608's avatar
fxy060608 已提交
71

fxy060608's avatar
fxy060608 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84
function isVueJs(id: string) {
  return (
    id.includes('plugin-vue:export-helper') ||
    (id.includes('/@vue/') && id.endsWith('.js'))
  )
}

function isDCloudJs(id: string) {
  return id.includes('/@dcloudio/') && id.endsWith('.js')
}

const chunkFileNameBlackList = ['main', 'pages.json', 'manifest.json']

fxy060608's avatar
fxy060608 已提交
85 86
function createMoveToVendorChunkFn(): GetManualChunk {
  const cache = new Map<string, boolean>()
fxy060608's avatar
fxy060608 已提交
87
  const inputDir = normalizePath(process.env.UNI_INPUT_DIR)
fxy060608's avatar
fxy060608 已提交
88
  return (id, { getModuleInfo }) => {
fxy060608's avatar
fxy060608 已提交
89
    id = normalizePath(id)
fxy060608's avatar
fxy060608 已提交
90
    if (
fxy060608's avatar
fxy060608 已提交
91 92 93 94 95
      isVueJs(id) ||
      isDCloudJs(id) ||
      (id.includes('node_modules') &&
        !isCSSRequest(id) &&
        staticImportedByEntry(id, getModuleInfo, cache))
fxy060608's avatar
fxy060608 已提交
96
    ) {
fxy060608's avatar
fxy060608 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
      debugChunk('common/vendor', id)
      return 'common/vendor'
    }
    const filename = id.split('?')[0]
    // 处理项目内的js,ts文件
    if (EXTNAME_JS_RE.test(filename) && filename.startsWith(inputDir)) {
      const chunkFileName = removeExt(
        normalizePath(path.relative(inputDir, filename))
      )
      if (
        !chunkFileNameBlackList.includes(chunkFileName) &&
        !hasJsonFile(chunkFileName) // 无同名的page,component
      ) {
        debugChunk(chunkFileName, id)
        return chunkFileName
      }
fxy060608's avatar
fxy060608 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    }
  }
}

function staticImportedByEntry(
  id: string,
  getModuleInfo: GetModuleInfo,
  cache: Map<string, boolean>,
  importStack: string[] = []
): boolean {
  if (cache.has(id)) {
    return cache.get(id) as boolean
  }
  if (importStack.includes(id)) {
    // circular deps!
    cache.set(id, false)
    return false
  }
  const mod = getModuleInfo(id)
  if (!mod) {
    cache.set(id, false)
    return false
  }

  if (mod.isEntry) {
    cache.set(id, true)
    return true
  }
  const someImporterIs = mod.importers.some((importer) =>
    staticImportedByEntry(
      importer,
      getModuleInfo,
      cache,
      importStack.concat(id)
    )
  )
  cache.set(id, someImporterIs)
  return someImporterIs
}