UNPKG

3.16 kBPlain TextView Raw
1import * as path from 'path'
2import * as fs from 'fs-extra'
3import * as t from 'babel-types'
4
5import {
6 printLog,
7 promoteRelativePath,
8 resolveScriptPath,
9 processTypeEnum,
10 REG_SCRIPT,
11 REG_TYPESCRIPT
12} from '@tarojs/helper'
13
14function getRelativePath (
15 rootPath: string,
16 sourceFilePath: string,
17 oriPath: string
18) {
19 // 处理以/开头的绝对路径,比如 /a/b
20 if (path.isAbsolute(oriPath)) {
21 if (oriPath.indexOf('/') !== 0) {
22 return ''
23 }
24 const vpath = path.resolve(rootPath, oriPath.substr(1))
25 if (!fs.existsSync(vpath)) {
26 return ''
27 }
28 let relativePath = path.relative(path.dirname(sourceFilePath), vpath)
29 relativePath = promoteRelativePath(relativePath)
30 if (relativePath.indexOf('.') !== 0) {
31 return './' + relativePath
32 }
33 return relativePath
34 }
35 // 处理非正常路径,比如 a/b
36 if (oriPath.indexOf('.') !== 0) {
37 const vpath = path.resolve(sourceFilePath, '..', oriPath)
38 if (fs.existsSync(vpath)) {
39 return './' + oriPath
40 }
41 }
42 return oriPath
43}
44
45export function analyzeImportUrl (
46 rootPath: string,
47 sourceFilePath: string,
48 scriptFiles: Set<string>,
49 source: t.StringLiteral,
50 value: string
51) {
52 const valueExtname = path.extname(value)
53 const rpath = getRelativePath(rootPath, sourceFilePath, value)
54 if (!rpath) {
55 printLog(processTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
56 return
57 }
58 if (rpath !== value) {
59 value = rpath
60 source.value = rpath
61 }
62 if (value.indexOf('.') === 0) {
63 if (REG_SCRIPT.test(valueExtname) || REG_TYPESCRIPT.test(valueExtname)) {
64 const vpath = path.resolve(sourceFilePath, '..', value)
65 let fPath = value
66 if (fs.existsSync(vpath)) {
67 fPath = vpath
68 } else {
69 printLog(processTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
70 }
71 scriptFiles.add(fPath)
72 } else {
73 let vpath = resolveScriptPath(path.resolve(sourceFilePath, '..', value))
74 if (vpath) {
75 if (!fs.existsSync(vpath)) {
76 printLog(processTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
77 } else {
78 if (fs.lstatSync(vpath).isDirectory()) {
79 if (fs.existsSync(path.join(vpath, 'index.js'))) {
80 vpath = path.join(vpath, 'index.js')
81 } else {
82 printLog(processTypeEnum.ERROR, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`)
83 return
84 }
85 }
86 let relativePath = path.relative(sourceFilePath, vpath)
87 const relativePathExtname = path.extname(relativePath)
88 scriptFiles.add(vpath)
89 relativePath = promoteRelativePath(relativePath)
90 if (/\.wxs/.test(relativePathExtname)) {
91 relativePath += '.js'
92 } else {
93 relativePath = relativePath.replace(relativePathExtname, '.js')
94 }
95 source.value = relativePath
96 }
97 }
98 }
99 }
100}
101
102export const incrementId = () => {
103 let n = 0
104 return () => (n++).toString()
105}