本文整理汇总了TypeScript中babel-types.importDeclaration函数的典型用法代码示例。如果您正苦于以下问题:TypeScript importDeclaration函数的具体用法?TypeScript importDeclaration怎么用?TypeScript importDeclaration使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了importDeclaration函数的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。
示例1: prepareBundleModule
/**
* Generate code containing import statements to all bundled modules and
* export statements to re-export their namespaces and exports.
*
* Example: a bundle containing files `module-a.js` and `module-b.js` would
* result in a prepareBundleModule result like:
*
* import * as $moduleA from './module-a.js';
* import * as $moduleB from './module-b.js';
* import $moduleBDefault from './module-b.js';
* export {thing1, thing2} from './module-a.js';
* export {thing3} from './module-b.js';
* export {$moduleA, $moduleB, $moduleBDefault};
*/
async function prepareBundleModule(
bundler: Bundler, manifest: BundleManifest, assignedBundle: AssignedBundle):
Promise<string> {
let bundleSource = babel.program([]);
const sourceAnalysis =
await bundler.analyzer.analyze([...assignedBundle.bundle.files]);
for (const sourceUrl of [...assignedBundle.bundle.files].sort()) {
const rebasedSourceUrl =
ensureLeadingDot(bundler.analyzer.urlResolver.relative(
stripUrlFileSearchAndHash(assignedBundle.url), sourceUrl));
const moduleDocument = getAnalysisDocument(sourceAnalysis, sourceUrl);
const moduleExports = getModuleExportNames(moduleDocument);
const starExportName =
getOrSetBundleModuleExportName(assignedBundle, sourceUrl, '*');
bundleSource.body.push(babel.importDeclaration(
[babel.importNamespaceSpecifier(babel.identifier(starExportName))],
babel.stringLiteral(rebasedSourceUrl)));
if (moduleExports.size > 0) {
bundleSource.body.push(babel.exportNamedDeclaration(
undefined, [babel.exportSpecifier(
babel.identifier(starExportName),
babel.identifier(starExportName))]));
bundleSource.body.push(babel.exportNamedDeclaration(
undefined,
[...moduleExports].map(
(e) => babel.exportSpecifier(
babel.identifier(e),
babel.identifier(getOrSetBundleModuleExportName(
assignedBundle, sourceUrl, e)))),
babel.stringLiteral(rebasedSourceUrl)));
}
}
const {code} = generate(bundleSource);
return code;
}
开发者ID:Polymer,项目名称:vulcanize,代码行数:49,代码来源:es6-module-bundler.ts
示例2: buildImportStatement
export function buildImportStatement (source: string, specifiers: string[] = [], defaultSpec?: string) {
return t.importDeclaration(
defaultSpec ? [defaultSpec, ...specifiers].map((spec, index) => {
if (index === 0) {
return t.importDefaultSpecifier(t.identifier(defaultSpec))
}
return t.importSpecifier(t.identifier(spec), t.identifier(spec))
}) : specifiers.map(s => t.importSpecifier(t.identifier(s), t.identifier(s))),
t.stringLiteral(source)
)
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:11,代码来源:utils.ts
示例3: babel7Transform
export default function transform<T> (options: Options): TransformResult {
const code = options.isTyped
? babel7Transform(options.code, {
parserOpts: {
sourceType: 'module',
plugins: [
'typescript',
'classProperties',
'jsx',
'trailingFunctionCommas',
'asyncFunctions',
'exponentiationOperator',
'asyncGenerators',
'objectRestSpread',
'decorators'
] as any[]
},
plugins: [
'@babel/plugin-transform-typescript'
]
}).code
: options.code
setting.sourceCode = code
// babel-traverse 无法生成 Hub
// 导致 Path#getSource|buildCodeFrameError 都无法直接使用
// 原因大概是 babylon.parse 没有生成 File 实例导致 scope 和 path 原型上都没有 `file`
// 将来升级到 babel@7 可以直接用 parse 而不是 transform
const ast = parse(code, {
parserOpts: {
sourceType: 'module',
plugins: [
'typescript',
'classProperties',
'jsx',
'flow',
'flowComment',
'trailingFunctionCommas',
'asyncFunctions',
'exponentiationOperator',
'asyncGenerators',
'objectRestSpread',
'decorators'
] as any[]
}
}).ast as t.File
// transformFromAst(ast, code)
let result
const componentSourceMap = new Map<string, string[]>()
const imageSource = new Set<string>()
let mainClass!: NodePath<t.ClassDeclaration>
let storeName!: string
let renderMethod!: NodePath<t.ClassMethod>
traverse(ast, {
ClassDeclaration (path) {
mainClass = path
},
ClassMethod (path) {
if (t.isIdentifier(path.node.key) && path.node.key.name === 'render') {
renderMethod = path
}
},
AwaitExpression (path) {
const isAsyncImported = ast.program.body.some(statement => {
return t.isImportDeclaration(statement) && statement.source.value === ASYNC_PACKAGE_NAME
})
if (!isAsyncImported) {
ast.program.body.unshift(
t.importDeclaration([], t.stringLiteral(ASYNC_PACKAGE_NAME))
)
}
},
JSXOpeningElement (path) {
const { name } = path.node.name as t.JSXIdentifier
if (name === 'Provider') {
const modules = path.scope.getAllBindings('module')
const providerBinding = Object.values(modules).some((m: Binding) => m.identifier.name === 'Provider')
if (providerBinding) {
path.node.name = t.jSXIdentifier('View')
const store = path.node.attributes.find(attr => attr.name.name === 'store')
if (store && t.isJSXExpressionContainer(store.value) && t.isIdentifier(store.value.expression)) {
storeName = store.value.expression.name
}
path.node.attributes = []
}
}
if (IMAGE_COMPONENTS.has(name)) {
for (const attr of path.node.attributes) {
if (
t.isIdentifier(attr) &&
attr.name.name === 'src'
) {
if (t.isStringLiteral(attr.value)) {
imageSource.add(attr.value.value)
} else if (t.isJSXExpressionContainer(attr.value)) {
if (t.isStringLiteral(attr.value.expression)) {
imageSource.add(attr.value.expression.value)
}
}
}
//.........这里部分代码省略.........
开发者ID:teachat8,项目名称:taro,代码行数:101,代码来源:index.ts
示例4: transform
//.........这里部分代码省略.........
}
}
}
// @TODO: bind 的处理待定
}
},
ImportDeclaration (path) {
const source = path.node.source.value
if (importSources.has(source)) {
throw codeFrameError(path.node, '无法在同一文件重复 import 相同的包。')
} else {
importSources.add(source)
}
const names: string[] = []
if (source === TARO_PACKAGE_NAME) {
isImportTaro = true
path.node.specifiers.push(
t.importSpecifier(t.identifier(INTERNAL_SAFE_GET), t.identifier(INTERNAL_SAFE_GET)),
t.importSpecifier(t.identifier(INTERNAL_GET_ORIGNAL), t.identifier(INTERNAL_GET_ORIGNAL)),
t.importSpecifier(t.identifier(INTERNAL_INLINE_STYLE), t.identifier(INTERNAL_INLINE_STYLE))
)
}
if (
source === REDUX_PACKAGE_NAME || source === MOBX_PACKAGE_NAME
) {
path.node.specifiers.forEach((s, index, specs) => {
if (s.local.name === 'Provider') {
specs.splice(index, 1)
specs.push(
t.importSpecifier(t.identifier('setStore'), t.identifier('setStore'))
)
}
})
}
path.traverse({
ImportDefaultSpecifier (path) {
const name = path.node.local.name
DEFAULT_Component_SET.has(name) || names.push(name)
},
ImportSpecifier (path) {
const name = path.node.imported.name
DEFAULT_Component_SET.has(name) || names.push(name)
if (source === TARO_PACKAGE_NAME && name === 'Component') {
path.node.local = t.identifier('__BaseComponent')
}
}
})
componentSourceMap.set(source, names)
}
})
if (!isImportTaro) {
ast.program.body.unshift(
t.importDeclaration([
t.importDefaultSpecifier(t.identifier('Taro')),
t.importSpecifier(t.identifier(INTERNAL_SAFE_GET), t.identifier(INTERNAL_SAFE_GET)),
t.importSpecifier(t.identifier(INTERNAL_GET_ORIGNAL), t.identifier(INTERNAL_GET_ORIGNAL)),
t.importSpecifier(t.identifier(INTERNAL_INLINE_STYLE), t.identifier(INTERNAL_INLINE_STYLE))
], t.stringLiteral('@tarojs/taro'))
)
}
if (!mainClass) {
throw new Error('未找到 Taro.Component 的类定义')
}
mainClass.node.body.body.forEach(handleThirdPartyComponent)
const storeBinding = mainClass.scope.getBinding(storeName)
mainClass.scope.rename('Component', '__BaseComponent')
if (storeBinding) {
const statementPath = storeBinding.path.getStatementParent()
if (statementPath) {
ast.program.body.forEach((node, index, body) => {
if (node === statementPath.node) {
body.splice(index + 1, 0, t.expressionStatement(
t.callExpression(t.identifier('setStore'), [
t.identifier(storeName)
])
))
}
})
}
}
resetTSClassProperty(mainClass.node.body.body)
if (options.isApp) {
renderMethod.replaceWith(
t.classMethod('method', t.identifier('_createData'), [], t.blockStatement([]))
)
return { ast } as TransformResult
}
result = new Transformer(mainClass, options.sourcePath, componentProperies).result
result.code = generate(ast).code
result.ast = ast
result.template = prettyPrint(result.template, {
max_char: 0
})
result.imageSrcs = Array.from(imageSource)
return result
}
开发者ID:topud,项目名称:taro,代码行数:101,代码来源:index.ts
示例5: parseAst
//.........这里部分代码省略.........
analyzeImportUrl(sourceFilePath, scriptFiles, source, value)
},
CallExpression (astPath) {
const node = astPath.node
const calleePath = astPath.get('callee')
const callee = calleePath.node
if (callee.type === 'Identifier') {
if (callee.name === 'require') {
const args = node.arguments as Array<t.StringLiteral>
const value = args[0].value
analyzeImportUrl(sourceFilePath, scriptFiles, args[0], value)
} else if (WX_GLOBAL_FN.has(callee.name)) {
calleePath.replaceWith(
t.memberExpression(t.identifier('Taro'), callee as t.Identifier)
)
needInsertImportTaro = true
}
} else if (callee.type === 'MemberExpression') {
const object = callee.object as t.Identifier
if (object.name === 'wx') {
(calleePath.get('object') as NodePath).replaceWith(t.identifier('Taro'))
needInsertImportTaro = true
}
}
}
})
},
exit (astPath) {
const bodyNode = astPath.get('body') as NodePath<t.Node>[]
const lastImport = bodyNode.filter(p => p.isImportDeclaration()).pop()
const hasTaroImport = bodyNode.some(p => p.isImportDeclaration() && p.node.source.value === '@tarojs/taro')
if (needInsertImportTaro && !hasTaroImport) {
(astPath.node as t.Program).body.unshift(
t.importDeclaration(
[t.importDefaultSpecifier(t.identifier('Taro'))],
t.stringLiteral('@tarojs/taro')
)
)
}
astPath.traverse({
StringLiteral (astPath) {
const value = astPath.node.value
const extname = path.extname(value)
if (extname && REG_IMAGE.test(extname) && !REG_URL.test(value)) {
let imageRelativePath: string
let sourceImagePath: string
let outputImagePath: string
if (path.isAbsolute(value)) {
sourceImagePath = path.join(self.root, value)
} else {
sourceImagePath = path.resolve(sourceFilePath, '..', value)
}
imageRelativePath = promoteRelativePath(path.relative(sourceFilePath, sourceImagePath))
outputImagePath = self.getDistFilePath(sourceImagePath)
if (fs.existsSync(sourceImagePath)) {
self.copyFileToTaro(sourceImagePath, outputImagePath)
printLog(processTypeEnum.COPY, '图片', self.generateShowPath(outputImagePath))
} else {
printLog(processTypeEnum.ERROR, '图片不存在', self.generateShowPath(sourceImagePath))
}
if (astPath.parentPath.isVariableDeclarator()) {
astPath.replaceWith(t.callExpression(t.identifier('require'), [t.stringLiteral(imageRelativePath)]))
} else if (astPath.parentPath.isJSXAttribute()) {
astPath.replaceWith(t.jSXExpressionContainer(t.callExpression(t.identifier('require'), [t.stringLiteral(imageRelativePath)])))
}
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:index.ts
示例6: parseJSCode
export function parseJSCode ({code, filePath, isEntryFile, projectConfig}) {
let ast
try {
ast = getJSAst(code, filePath)
} catch (e) {
throw e
}
const styleFiles: string[] = []
const pages: string[] = [] // app.js 里面的config 配置里面的 pages
const iconPaths: string[] = [] // app.js 里面的config 配置里面的需要引入的 iconPath
let hasAddReactImportDefaultName = false
let providorImportName
let storeName
let hasAppExportDefault
let classRenderReturnJSX
let hasConstructor = false
let hasComponentDidMount = false
let hasComponentDidShow = false
let hasComponentDidHide = false
let hasComponentWillUnmount = false
traverse(ast, {
ClassExpression: ClassDeclarationOrExpression,
ClassDeclaration: ClassDeclarationOrExpression,
ImportDeclaration (astPath) {
const node = astPath.node as t.ImportDeclaration
const source = node.source
let value = source.value
const valueExtname = path.extname(value)
const specifiers = node.specifiers
const pathAlias = projectConfig.alias || {}
if (Util.isAliasPath(value, pathAlias)) {
source.value = value = Util.replaceAliasPath(filePath, value, pathAlias)
}
// 引入的包为 npm 包
if (!Util.isNpmPkg(value)) {
// import 样式处理
if (REG_STYLE.test(valueExtname)) {
const stylePath = path.resolve(path.dirname(filePath), value)
if (styleFiles.indexOf(stylePath) < 0) {
styleFiles.push(stylePath)
}
}
if (value.indexOf('.') === 0) {
const pathArr = value.split('/')
if (pathArr.indexOf('pages') >= 0) {
astPath.remove()
} else if (REG_SCRIPTS.test(value) || path.extname(value) === '') {
const absolutePath = path.resolve(filePath, '..', value)
const dirname = path.dirname(absolutePath)
const extname = path.extname(absolutePath)
const realFilePath = Util.resolveScriptPath(path.join(dirname, path.basename(absolutePath, extname)))
const removeExtPath = realFilePath.replace(path.extname(realFilePath), '')
node.source = t.stringLiteral(Util.promoteRelativePath(path.relative(filePath, removeExtPath)).replace(/\\/g, '/'))
}
}
return
}
if (value === PACKAGES['@tarojs/taro']) {
const specifier = specifiers.find(item => item.type === 'ImportDefaultSpecifier')
if (specifier) {
hasAddReactImportDefaultName = true
taroImportDefaultName = specifier.local.name
specifier.local.name = reactImportDefaultName
} else if (!hasAddReactImportDefaultName) {
hasAddReactImportDefaultName = true
node.specifiers.unshift(
t.importDefaultSpecifier(t.identifier(reactImportDefaultName))
)
}
// 删除从@tarojs/taro引入的 React
specifiers.forEach((item, index) => {
if (item.type === 'ImportDefaultSpecifier') {
specifiers.splice(index, 1)
}
})
const taroApisSpecifiers: t.ImportSpecifier[] = []
specifiers.forEach((item, index) => {
if ((item as t.ImportSpecifier).imported && taroApis.indexOf((item as t.ImportSpecifier).imported.name) >= 0) {
taroApisSpecifiers.push(
t.importSpecifier(t.identifier((item as t.ImportSpecifier).local.name), t.identifier((item as t.ImportSpecifier).imported.name)))
specifiers.splice(index, 1)
}
})
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'])))
}
if (!specifiers.length) {
astPath.remove()
}
} else if (value === PACKAGES['@tarojs/redux']) {
const specifier = specifiers.find(item => {
return t.isImportSpecifier(item) && item.imported.name === providerComponentName
})
if (specifier) {
//.........这里部分代码省略.........
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:transformJS.ts
注:本文中的babel-types.importDeclaration函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论