Skip to content

Commit

Permalink
feat(transformer): this.state 的变量和 render 的自定义变量重名时警告,close #1385
Browse files Browse the repository at this point in the history
  • Loading branch information
yuche committed Jan 9, 2019
1 parent 8bd95c8 commit 2890c67
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/taro-transformer-wx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export default function transform (options: Options): TransformResult {
require('babel-plugin-transform-flow-strip-types'),
[require('babel-plugin-transform-define').default, options.env]
].concat(process.env.ESLINT === 'false' || options.isNormal || options.isTyped ? [] : eslintValidation)
.concat((process.env.NODE_ENV === 'test') ? [] : require('babel-plugin-minify-dead-code'))
// .concat((process.env.NODE_ENV === 'test') ? [] : require('babel-plugin-minify-dead-code'))
}).ast as t.File
if (options.isNormal) {
return { ast } as any
Expand Down
40 changes: 39 additions & 1 deletion packages/taro-transformer-wx/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -956,12 +956,50 @@ export class RenderParser {
}

private visitors: Visitor = {
VariableDeclarator (path) {
VariableDeclarator: (path) => {
const init = path.get('init')
const id = path.get('id')
const ifStem = init.findParent(p => p.isIfStatement())
if (ifStem && init.node === null) {
init.replaceWith(t.identifier('undefined'))
}
let isDerivedFromState = false
if (init.isMemberExpression()) {
const object = init.get('object')
if (object.isMemberExpression() && object.get('object').isThisExpression() && object.get('property').isIdentifier({ name: 'state' })) {
isDerivedFromState = true
}
if (object.isThisExpression() && init.get('property').isIdentifier({ name: 'state' })) {
isDerivedFromState = true
}
}
if (!isDerivedFromState) {
const errMsg = 'Warning: render 函数定义一个不从 this.state 解构或赋值而来的变量,此变量又与 this.state 下的变量重名可能会导致无法渲染。'
if (id.isIdentifier()) {
const name = id.node.name
if (this.initState.has(name)) {
// tslint:disable-next-line
console.log(codeFrameError(id.node, errMsg).message)
}
}
if (id.isObjectPattern()) {
const { properties } = id.node
for (const p of properties) {
if (t.isIdentifier(p)) {
if (this.initState.has(p.name)) {
// tslint:disable-next-line
console.log(codeFrameError(id.node, errMsg).message)
}
}
if (t.isSpreadProperty(p) && t.isIdentifier(p.argument)) {
if (this.initState.has(p.argument.name)) {
// tslint:disable-next-line
console.log(codeFrameError(id.node, errMsg).message)
}
}
}
}
}
},
JSXEmptyExpression (path) {
const parent = path.parentPath
Expand Down

0 comments on commit 2890c67

Please sign in to comment.