Skip to content

Commit

Permalink
feat(rn): 优化插入 React Import 代码的判断逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
Pines-Cheng committed Aug 5, 2019
1 parent 95b9f30 commit e2cb224
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions packages/taro-cli/src/rn/transformJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ export function parseJSCode ({code, filePath, isEntryFile, projectConfig}) {
let hasComponentDidShow = false
let hasComponentDidHide = false
let hasComponentWillUnmount = false
let hasJSX = false

traverse(ast, {
ClassExpression: ClassDeclarationOrExpression,
Expand All @@ -245,7 +246,7 @@ export function parseJSCode ({code, filePath, isEntryFile, projectConfig}) {
if (Util.isAliasPath(value, pathAlias)) {
source.value = value = Util.replaceAliasPath(filePath, value, pathAlias)
}
// 引入的包为 npm 包
// 引入的包为非 npm 包
if (!Util.isNpmPkg(value)) {
// import 样式处理
if (REG_STYLE.test(valueExtname)) {
Expand Down Expand Up @@ -299,8 +300,6 @@ export function parseJSCode ({code, filePath, isEntryFile, projectConfig}) {
}
})
source.value = PACKAGES['@tarojs/taro-rn']
// insert React
astPath.insertBefore(template(`import React from 'react'`, babylonConfig as any)())

if (taroApisSpecifiers.length) {
astPath.insertBefore(t.importDeclaration(taroApisSpecifiers, t.stringLiteral(PACKAGES['@tarojs/taro-rn'])))
Expand Down Expand Up @@ -383,6 +382,11 @@ export function parseJSCode ({code, filePath, isEntryFile, projectConfig}) {
hasAppExportDefault = true
}
},
JSXElement: {
exit (astPath: NodePath<t.JSXElement>) {
hasJSX = true
}
},
JSXOpeningElement: {
enter (astPath) {
const node = astPath.node as t.JSXOpeningElement
Expand Down Expand Up @@ -496,6 +500,10 @@ export function parseJSCode ({code, filePath, isEntryFile, projectConfig}) {
}
}
})
// insert React
if (hasJSX) {
node.body.unshift(template(`import React from 'react'`, babylonConfig as any)())
}
// import Taro from @tarojs/taro-rn
if (taroImportDefaultName) {
const importTaro = template(
Expand Down

0 comments on commit e2cb224

Please sign in to comment.