Skip to content

Commit

Permalink
feat(cli): taroize 转换时 jsx 中引用图片处理
Browse files Browse the repository at this point in the history
  • Loading branch information
luckyadam committed Dec 3, 2018
1 parent 5c8ca3a commit d608d8c
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion packages/taro-cli/src/convertor.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ class Convertor {
parseAst ({ ast, sourceFilePath, outputFilePath, importStylePath, depComponents, imports = [] }) {
const scriptFiles = new Set()
const self = this
const images = new Map()
const IMPORT_IMAGE_PREFIX = 'anonymous__img__'
let imageCounter = 0
traverse(ast, {
Program: {
enter (astPath) {
Expand All @@ -130,10 +133,28 @@ class Convertor {
const value = args[0].value
analyzeImportUrl(sourceFilePath, scriptFiles, args[0], value)
}
},
JSXOpeningElement (astPath) {
if (astPath.get('name').isJSXIdentifier({ name: 'Image' })) {
astPath.traverse({
JSXAttribute (astPath) {
if (astPath.get('name').isJSXIdentifier({ name: 'src' })) {
const value = astPath.get('value')
if (value.isStringLiteral()) {
const imgSrc = value.node.value
const imgImportName = IMPORT_IMAGE_PREFIX + imageCounter
images.set(imgImportName, imgSrc)
astPath.replaceWith(t.jSXAttribute(astPath.get('name').node, t.jSXExpressionContainer(t.identifier(imgImportName))))
imageCounter++
}
}
}
})
}
}
})
},
exit (astPath) {
exit: (astPath) => {
const lastImport = astPath.get('body').filter(p => p.isImportDeclaration()).pop()
if (lastImport) {
if (importStylePath) {
Expand Down Expand Up @@ -161,6 +182,25 @@ class Convertor {
})())
})
}
if (images && images.size) {
images.forEach((image, key) => {
let imageRelativePath = null
let sourceImagePath = null
let outputImagePath = null
if (path.isAbsolute(image)) {
sourceImagePath = path.join(this.root, image)
} else {
sourceImagePath = path.resolve(sourceFilePath, '..', image)
}
imageRelativePath = promoteRelativePath(path.relative(sourceFilePath, sourceImagePath))
outputImagePath = this.getDistFilePath(sourceImagePath)
this.copyFileToTaro(sourceImagePath, outputImagePath)
printLog(pocessTypeEnum.COPY, '图片', this.generateShowPath(outputImagePath))
lastImport.insertAfter(template(`import ${key} from '${imageRelativePath}'`, {
sourceType: 'module'
})())
})
}
}
}
}
Expand Down

0 comments on commit d608d8c

Please sign in to comment.