本文整理汇总了TypeScript中@babel/traverse.default函数的典型用法代码示例。如果您正苦于以下问题:TypeScript default函数的具体用法?TypeScript default怎么用?TypeScript default使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了default函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。
示例1: extractStyles
//.........这里部分代码省略.........
// Generate a UID that's unique in the program scope
let boxComponentName: string | undefined;
traverse(ast, {
Program(traversePath: TraversePath) {
boxComponentName = generateUid(traversePath.scope, 'Box');
},
});
// per-file cache of evaluated bindings
const bindingCache = {};
const traverseOptions: { JSXElement: VisitNodeObject<t.JSXElement> } = {
JSXElement: {
enter(traversePath: TraversePath<t.JSXElement>) {
const node = traversePath.node.openingElement;
if (
// skip non-identifier opening elements (member expressions, etc.)
!t.isJSXIdentifier(node.name) ||
// skip non-jsxstyle components
!validComponents.hasOwnProperty(node.name.name)
) {
return;
}
// Remember the source component
const originalNodeName = node.name.name;
const srcKey = validComponents[originalNodeName];
node.name.name = boxComponentName!;
// prepend initial styles
const initialStyles = defaultStyleAttributes[srcKey];
if (initialStyles) {
node.attributes = [...initialStyles, ...node.attributes];
}
const attemptEval = !evaluateVars
? evaluateAstNode
: (() => {
// Generate scope object at this level
const staticNamespace = getStaticBindingsForScope(
traversePath.scope,
whitelistedModules,
sourceFileName,
bindingCache
);
const evalContext = vm.createContext(staticNamespace);
// called when evaluateAstNode encounters a dynamic-looking prop
const evalFn = (n: t.Node) => {
// variable
if (t.isIdentifier(n)) {
invariant(
staticNamespace.hasOwnProperty(n.name),
'identifier not in staticNamespace'
);
return staticNamespace[n.name];
}
return vm.runInContext(`(${generate(n).code})`, evalContext);
};
return (n: t.Node) => evaluateAstNode(n, evalFn);
})();
开发者ID:petehunt,项目名称:jsxstyle,代码行数:67,代码来源:extractStyles.ts
示例2: process
export default function process(source: string, ast: t.File): Changes {
const tokens: Array<Token> = ast.tokens;
const insertions: Array<Insertion> = [];
const removals: Array<Removal> = [];
traverse(ast, {
VariableDeclaration(path: NodePath<t.VariableDeclaration>): void {
const { node, parent } = path;
const isForInit = (
(t.isForStatement(parent) && parent.init === node) ||
((t.isForInStatement(parent) || t.isForOfStatement(parent)) && parent.left === node)
);
if (!isForInit) {
checkForSemicolon(node);
}
},
ExpressionStatement(path: NodePath<t.ExpressionStatement>): void {
checkForSemicolon(path.node);
},
ReturnStatement(path: NodePath<t.ReturnStatement>): void {
checkForSemicolon(path.node);
},
ThrowStatement(path: NodePath<t.ThrowStatement>): void {
checkForSemicolon(path.node);
},
DoWhileStatement(path: NodePath<t.DoWhileStatement>): void {
checkForSemicolon(path.node);
},
DebuggerStatement(path: NodePath<t.DebuggerStatement>): void {
checkForSemicolon(path.node);
},
BreakStatement(path: NodePath<t.BreakStatement>): void {
checkForSemicolon(path.node);
},
ContinueStatement(path: NodePath<t.ContinueStatement>): void {
checkForSemicolon(path.node);
},
ImportDeclaration(path: NodePath<t.ImportDeclaration>): void {
checkForSemicolon(path.node);
},
ExportAllDeclaration(path: NodePath<t.ExportAllDeclaration>): void {
checkForSemicolon(path.node);
},
ExportNamedDeclaration(path: NodePath<t.ExportNamedDeclaration>): void {
if (!path.node.declaration) {
checkForSemicolon(path.node);
}
},
ExportDefaultDeclaration(path: NodePath<t.ExportDefaultDeclaration>): void {
const { node } = path;
const { declaration } = node;
if (t.isClassDeclaration(declaration) || t.isFunctionDeclaration(declaration)) {
if (!declaration.id) {
checkForSemicolon(node);
}
} else {
checkForSemicolon(node);
}
},
EmptyStatement(path: NodePath<t.EmptyStatement>): void {
const { node, parent } = path;
if (
!t.isForStatement(parent) &&
!t.isForOfStatement(parent) &&
!t.isForInStatement(parent) &&
!t.isWhileStatement(parent) &&
!t.isDoWhileStatement(parent)
) {
remove(startOfNode(node), endOfNode(node));
}
},
ClassBody(path: NodePath<t.ClassBody>): void {
checkClassBodyForSemicolon(tokenAfterToken(firstTokenOfNode(path.node)));
},
ClassMethod(path: NodePath<t.ClassMethod>): void {
checkClassBodyForSemicolon(tokenAfterToken(lastTokenOfNode(path.node)));
}
});
return { insertions, removals };
/**
* Checks a node to see if it's followed by a semicolon.
//.........这里部分代码省略.........
开发者ID:eventualbuddha,项目名称:automatic-semicolon-insertion,代码行数:101,代码来源:index.ts
示例3: traverse
export function traverse(ast: babel.Node, visitor: Visitor): void {
babelTraverse(ast, {
enter(path) {
dispatchVisitMethods(
['enter', `enter${path.type}` as keyof Visitor], path, visitor);
},
exit(path) {
dispatchVisitMethods(
['leave', `leave${path.type}` as keyof Visitor], path, visitor);
},
noScope: !babel.isFile(ast),
});
}
开发者ID:MehdiRaash,项目名称:tools,代码行数:14,代码来源:estraverse-shim.ts
示例4: inferReturnFromBody
export function inferReturnFromBody(node: babel.Function): {type: string}|
undefined {
if (node.async === true || node.generator === true) {
// Async functions always return promises, and generators always return
// iterators, so they are never void.
return undefined;
}
if (babel.isArrowFunctionExpression(node) &&
!babel.isBlockStatement(node.body)) {
// An arrow function that immediately returns a value (e.g. () => 'foo').
return undefined;
}
let returnsVoid = true;
babelTraverse(node, {
ReturnStatement(path) {
const statement = path.node;
// The typings claim that statement.argument is always an Expression, but
// actually when there is no argument it is null.
if (statement.argument !== null) {
returnsVoid = false;
path.stop();
}
},
// If this function contains another function, don't traverse into it. Only
// return statements in the immediate function scope matter.
FunctionDeclaration(path) {
path.skip();
},
FunctionExpression(path) {
path.skip();
},
ClassMethod(path) {
path.skip();
},
ArrowFunctionExpression(path) {
path.skip();
},
ObjectMethod(path) {
path.skip();
},
noScope: true
});
if (returnsVoid) {
return {type: 'void'};
}
return undefined;
}
开发者ID:Polymer,项目名称:tools,代码行数:48,代码来源:esutil.ts
示例5: getEventComments
export function getEventComments(node: babel.Node): Map<string, ScannedEvent> {
const eventComments = new Set<string>();
babelTraverse(node, {
enter(path: NodePath) {
const node = path.node;
[...(node.leadingComments || []), ...(node.trailingComments || [])]
.map((commentAST) => commentAST.value)
.filter((comment) => comment.indexOf('@event') !== -1)
.forEach((comment) => eventComments.add(comment));
},
noScope: true,
});
const events = [...eventComments]
.map(
(comment) => annotateEvent(jsdoc.parseJsdoc(
jsdoc.removeLeadingAsterisks(comment).trim())))
.filter((ev) => !!ev)
.sort((ev1, ev2) => ev1.name.localeCompare(ev2.name));
return new Map(events.map((e) => [e.name, e] as [string, ScannedEvent]));
}
开发者ID:Polymer,项目名称:tools,代码行数:21,代码来源:esutil.ts
示例6: Error
describe('getSourceModule', () => {
const ast = parse(`
const Thing1 = require('thing');
const {Destructured1} = require('destructured');
const {Original: Reassigned1} = require('reassigned');
import Thing2 from 'thing';
import {Destructured2} from 'destructured';
import {Original as Reassigned2} from 'reassigned';
<Thing1 />;
<Thing2 />;
<Destructured1 />;
<Destructured2 />;
<Reassigned1 />;
<Reassigned2 />;
`);
const testItems: Record<string, any> = {};
traverse(ast, {
JSXElement(path) {
const node = path.node.openingElement;
const nodeName = node.name;
if (!t.isJSXIdentifier(nodeName)) {
throw new Error(
'Received invalid node name: ' + generate(node.name).code
);
}
testItems[nodeName.name] = {
node,
scope: path.scope,
};
},
});
it('traverses the source correctly', () => {
expect(Object.keys(testItems)).toEqual([
'Thing1',
'Thing2',
'Destructured1',
'Destructured2',
'Reassigned1',
'Reassigned2',
]);
});
it('handles regular requires', () => {
const { node, scope } = testItems.Thing1;
const itemName = node.name.name;
const sourceModule = getSourceModuleForItem(itemName, scope);
expect(sourceModule).not.toBeNull();
expect(sourceModule.destructured).toEqual(false);
expect(sourceModule.imported).toEqual('Thing1');
expect(sourceModule.local).toEqual('Thing1');
expect(sourceModule.sourceModule).toEqual('thing');
});
it('handles destructured requires', () => {
const { node, scope } = testItems.Destructured1;
const itemName = node.name.name;
const sourceModule = getSourceModuleForItem(itemName, scope);
expect(sourceModule).not.toBeNull();
expect(sourceModule.destructured).toEqual(true);
expect(sourceModule.imported).toEqual('Destructured1');
expect(sourceModule.local).toEqual('Destructured1');
expect(sourceModule.sourceModule).toEqual('destructured');
});
it('handles reassigned requires', () => {
const { node, scope } = testItems.Reassigned1;
const itemName = node.name.name;
const sourceModule = getSourceModuleForItem(itemName, scope);
expect(sourceModule).not.toBeNull();
expect(sourceModule.destructured).toEqual(true);
expect(sourceModule.imported).toEqual('Original');
expect(sourceModule.local).toEqual('Reassigned1');
expect(sourceModule.sourceModule).toEqual('reassigned');
});
it('handles regular imports', () => {
const { node, scope } = testItems.Thing2;
const itemName = node.name.name;
const sourceModule = getSourceModuleForItem(itemName, scope);
expect(sourceModule).not.toBeNull();
expect(sourceModule.destructured).toEqual(false);
expect(sourceModule.imported).toEqual('Thing2');
expect(sourceModule.local).toEqual('Thing2');
expect(sourceModule.sourceModule).toEqual('thing');
});
it('handles destructured imports', () => {
const { node, scope } = testItems.Destructured2;
const itemName = node.name.name;
const sourceModule = getSourceModuleForItem(itemName, scope);
expect(sourceModule).not.toBeNull();
//.........这里部分代码省略.........
开发者ID:petehunt,项目名称:jsxstyle,代码行数:101,代码来源:getSourceModule.spec.ts
示例7: Identifier
Identifier(path) {
console.log("Visiting: " + path.node.name);
}
};
// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse
const code = `function square(n) {
return n * n;
}`;
const ast = parse(code);
traverse(ast, {
enter(path) {
const node = path.node;
if (t.isIdentifier(node) && node.name === "n") {
node.name = "x";
}
}
});
// Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#writing-your-first-babel-plugin
const v1: Visitor = {
BinaryExpression(path) {
if (t.isIdentifier(path.node.left)) {
// ...
}
path.replaceWith(
t.binaryExpression("**", path.node.left, t.numericLiteral(2))
);
path.parentPath.replaceWith(
开发者ID:AlexGalays,项目名称:DefinitelyTyped,代码行数:32,代码来源:babel__traverse-tests.ts
示例8: outerFunction
describe('getStaticBindingsForScope', () => {
const ast = parse(`
const outerLiteral = 42;
const outerObject = {
value: 69 * 420,
};
import LC from './LC';
import { blue } from './LC';
import { Inline, Block } from 'jsxstyle';
function outerFunction(innerParam1, innerParam2) {
const innerLiteral = 'wow';
const innerObject = {};
const nullLiteral = null;
<Inline />;
return <Block
prop1={innerLiteral}
prop2={LC.staticValue}
prop3={outerLiteral}
/>;
}
`);
const testItems: Record<
string,
{ attrs: Record<string, any>; scope: any }
> = {};
traverse(ast, {
JSXElement(traversePath) {
const node = traversePath.node.openingElement;
const nodeName = node.name;
if (!t.isJSXIdentifier(nodeName)) {
throw new Error(
'Received invalid node name: ' + generate(node.name).code
);
}
testItems[nodeName.name] = {
attrs: {},
scope: traversePath.scope,
};
node.attributes.forEach(attr => {
if (
!t.isJSXAttribute(attr) ||
typeof attr.name.name !== 'string' ||
!t.isJSXExpressionContainer(attr.value)
) {
throw new Error(
'Received invalid JSXAttribute: ' + generate(attr).code
);
}
testItems[nodeName.name].attrs[attr.name.name] = attr.value.expression;
});
},
});
it('traverses the source correctly', () => {
expect(Object.keys(testItems)).toEqual(['Inline', 'Block']);
expect(Object.keys(testItems.Block.attrs)).toEqual([
'prop1',
'prop2',
'prop3',
]);
});
it('extracts static bindings and utilises the cache', () => {
const bindingCache = {};
const setFn = jest.fn();
const getFn = jest.fn();
const thingsToSet = [];
const thingsToGet = [];
const proxiedCache = new Proxy(bindingCache, {
set(target, name, value) {
setFn();
thingsToSet.push(name);
return Reflect.set(target, name, value);
},
getOwnPropertyDescriptor(target, name) {
getFn();
thingsToGet.push(name);
return Reflect.getOwnPropertyDescriptor(target, name);
},
});
const blockBindings = getStaticBindingsForScope(
testItems.Block.scope,
whitelistedModules,
path.resolve(__dirname, 'mock', 'demo.js'),
proxiedCache
);
expect(blockBindings).toEqual({
blue: 'blueberry',
innerLiteral: 'wow',
LC: require('./mock/LC'),
nullLiteral: null,
outerLiteral: 42,
//.........这里部分代码省略.........
开发者ID:petehunt,项目名称:jsxstyle,代码行数:101,代码来源:getStaticBindingsForScope.spec.ts
注:本文中的@babel/traverse.default函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论