本文整理汇总了TypeScript中babel-core.transformFromAst函数的典型用法代码示例。如果您正苦于以下问题:TypeScript transformFromAst函数的具体用法?TypeScript transformFromAst怎么用?TypeScript transformFromAst使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了transformFromAst函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: getFileAstAsync
async function getFileAstAsync(path: string, options: FableCompilerOptions, info: CompilationInfo) {
let ast: Babel.BabelFileResult | undefined;
if (FSHARP_EXT.test(path)) {
// return Babel AST from F# file
const fableMsg = JSON.stringify(Object.assign({}, options.fable, { path }));
const response = await fableUtils.client.send(options.port as number, fableMsg);
const babelAst = JSON.parse(response);
if (babelAst.error) {
throw new Error(babelAst.error);
}
addLogs(babelAst.logs, info);
ast = Babel.transformFromAst(babelAst, undefined, { code: false });
} else {
// return Babel AST from JS file
path = JAVASCRIPT_EXT.test(path) ? path : path + ".js";
if (fs.existsSync(path)) {
try {
ast = Babel.transformFileSync(path, { code: false });
} catch (err) {
const log = `${path}(1,1): error BABEL: ${err.message}`;
addLogs({ error: [log] }, info);
}
} else {
console.log(`fable: Skipping missing JS file: ${path}`);
}
}
return ast;
}
示例2: transformAndSaveAst
function transformAndSaveAst(fullPath: string, ast: any, options: FableCompilerOptions, info: CompilationInfo) {
// resolve output paths
const outPath = getOutPath(fullPath, info) + ".js";
const jsPath = join(options.outDir, outPath);
const jsDir = Path.dirname(jsPath);
ensureDirExists(jsDir);
// set sourcemap paths
const code: string | undefined = undefined;
const babelOptions = Object.assign({}, options.babel) as Babel.TransformOptions;
if (babelOptions.sourceMaps) {
// code = fs.readFileSync(fullPath, "utf8");
const relPath = Path.relative(jsDir, fullPath);
babelOptions.sourceFileName = relPath.replace(/\\/g, "/");
babelOptions.sourceMapTarget = Path.basename(outPath);
}
babelOptions.plugins = (babelOptions.plugins || [])
.concat(getResolvePathPlugin(jsDir, options));
// transform and save
let result = Babel.transformFromAst(ast, code, babelOptions);
if (options.prepack) {
const prepack = require("prepack");
result = prepack.prepackFromAst(result.ast, result.code, options.prepack);
}
fs.writeFileSync(jsPath, result.code);
if (result.map) {
fs.appendFileSync(jsPath, "\n//# sourceMappingURL=" + Path.basename(jsPath) + ".map");
fs.writeFileSync(jsPath + ".map", JSON.stringify(result.map));
}
console.log(`fable: Compiled ${Path.relative(process.cwd(), fullPath)}`);
}
示例3: babelify
export function babelify(babelAst: BabelAst, opts: FableOptions): BabelFile[] {
var outDir = pathJoin(opts.workingDir, opts.outDir);
var babelOpts: babel.TransformOptions = {
babelrc: opts.babelrc || false,
filename: babelAst.fileName,
// sourceRoot: outDir,
presets: opts.babel.presets,
plugins: opts.babel.plugins,
};
var fsCode = null;
// The F# code is only necessary when generating source maps
if (opts.sourceMaps && babelAst.originalFileName) {
try {
fsCode = fs.readFileSync(babelAst.originalFileName).toString();
babelOpts.sourceMaps = opts.sourceMaps,
babelOpts.sourceMapTarget = path.basename(babelAst.fileName),
babelOpts.sourceFileName = path.relative(path.dirname(babelAst.fileName),
babelAst.originalFileName.replace(/\\/g, '/'));
}
catch (err) {
// Do nothing
}
}
var parsed = babel.transformFromAst(babelAst as any, fsCode, babelOpts);
var res = [{
isEntry: babelAst.isEntry,
fileName: babelAst.fileName,
code: parsed.code,
map: parsed.map
}];
// Compile JS includes
if (Array.isArray(babelAst.jsIncludes))
babelAst.jsIncludes.forEach(js => {
parsed = babel.transformFileSync(js.sourcePath, babelOpts);
res.push({
isEntry: false,
fileName: pathJoin(outDir, "js_includes/" + js.name) + ".js",
code: parsed.code,
map: parsed.map
});
});
var timestamp = " at " + (new Date()).toLocaleTimeString();
for (var i=0; i<res.length; i++) {
stdoutLog("Compiled " + path.relative(outDir, res[i].fileName) + timestamp);
}
return res;
}
示例4: getFileAstAsync
async function getFileAstAsync(path: string, options: FableCompilerOptions) {
let result: Babel.BabelFileResult | undefined;
if (FSHARP_EXT.test(path)) {
// return Babel AST from F# file
const fableMsg = JSON.stringify(Object.assign({}, options.fable, { path }));
const babelAst = JSON.parse(await client.send(options.port, fableMsg));
if (babelAst.error) { throw new Error(babelAst.error); }
Object.keys(babelAst.logs || {}).forEach((key) => {
ensureArray(babelAst.logs[key]).forEach(
(log: string) => output(key)(`${key} ==> ${log}`));
});
result = Babel.transformFromAst(babelAst, undefined, { code: false });
} else {
// return Babel AST from JS file
path = JAVASCRIPT_EXT.test(path) ? path : path + ".js";
if (fs.existsSync(path)) {
result = Babel.transformFileSync(path, { code: false });
}
}
return result;
}
示例5: transformAndSaveAst
function transformAndSaveAst(fullPath: string, ast: any, options: FableCompilerOptions) {
// resolve output paths
const outPath = getOutPath(fullPath) + ".js";
const jsPath = Path.join(options.outDir, outPath);
const jsDir = Path.dirname(jsPath);
ensureDirExists(jsDir);
// set sourcemap paths
const code: string | undefined = undefined;
if (options.babel && options.babel.sourceMaps) {
// code = fs.readFileSync(fullPath, "utf8");
const relPath = Path.relative(jsDir, fullPath);
options.babel.sourceFileName = relPath.replace(/\\/g, "/");
options.babel.sourceMapTarget = Path.basename(outPath);
}
// transform and save
let result = Babel.transformFromAst(ast, code, options.babel);
if (options.prepack) {
const prepack = require("prepack");
result = prepack.prepackFromAst(result.ast, result.code, options.prepack);
}
if (result && result.code) { fs.writeFileSync(jsPath, result.code); }
if (result && result.map) { fs.writeFileSync(jsPath + ".map", JSON.stringify(result.map)); }
console.log(`Fable compiled: ${fullPath}`);
}
示例6: parseComponentExportAst
export function parseComponentExportAst (ast: t.File, componentName: string, componentPath: string, componentType: string): string | null {
const {
constantsReplaceList
} = getBuildData()
let componentRealPath: string | null = null
let importExportName
ast = babel.transformFromAst(ast, '', {
plugins: [
[require('babel-plugin-transform-define').default, constantsReplaceList]
]
}).ast as t.File
traverse(ast, {
ExportNamedDeclaration (astPath) {
const node = astPath.node
const specifiers = node.specifiers
const source = node.source
if (source && source.type === 'StringLiteral') {
specifiers.forEach(specifier => {
const exported = specifier.exported
if (_.kebabCase(exported.name) === componentName) {
componentRealPath = resolveScriptPath(path.resolve(path.dirname(componentPath), source.value))
}
})
} else {
specifiers.forEach(specifier => {
const exported = specifier.exported
if (_.kebabCase(exported.name) === componentName) {
importExportName = exported.name
}
})
}
},
ExportDefaultDeclaration (astPath) {
const node = astPath.node
const declaration = node.declaration as t.Identifier
if (componentType === 'default') {
importExportName = declaration.name
}
},
CallExpression (astPath) {
if (astPath.get('callee').isIdentifier({ name: 'require' })) {
const arg = astPath.get('arguments')[0]
if (t.isStringLiteral(arg.node)) {
componentRealPath = resolveScriptPath(path.resolve(path.dirname(componentPath), arg.node.value))
}
}
},
Program: {
exit (astPath) {
astPath.traverse({
ImportDeclaration (astPath) {
const node = astPath.node
const specifiers = node.specifiers
const source = node.source
if (importExportName) {
specifiers.forEach(specifier => {
const local = specifier.local
if (local.name === importExportName) {
componentRealPath = resolveScriptPath(path.resolve(path.dirname(componentPath), source.value))
}
})
}
}
})
}
}
})
return componentRealPath
}
示例7: parseAst
export function parseAst (
type: PARSE_AST_TYPE,
ast: t.File,
depComponents: IComponentObj[],
sourceFilePath: string,
filePath: string,
npmSkip: boolean = false
): IParseAstReturn {
const styleFiles: string[] = []
const scriptFiles: string[] = []
const jsonFiles: string[] = []
const mediaFiles: string[] = []
const {
appPath,
nodeModulesPath,
npmOutputDir,
sourceDir,
outputDir,
buildAdapter,
constantsReplaceList,
isProduction,
npmConfig,
alias: pathAlias,
compileInclude,
projectConfig
} = getBuildData()
const notExistNpmList = getNotExistNpmList()
const taroMiniAppFramework = `@tarojs/taro-${buildAdapter}`
let configObj: IConfig = {}
let componentClassName: string = ''
let taroJsReduxConnect: string = ''
let taroImportDefaultName
let needExportDefault = false
let exportTaroReduxConnected: string | null = null
const isQuickApp = buildAdapter === BUILD_TYPES.QUICKAPP
const cannotRemoves = [taroJsFramework, 'react', 'nervjs']
let hasComponentDidHide
let hasComponentDidShow
let hasComponentWillMount
let hasEnablePageScroll
if (isQuickApp) {
cannotRemoves.push(taroJsComponents)
}
const taroSelfComponents = new Set<string>()
ast = babel.transformFromAst(ast, '', {
plugins: [
[require('babel-plugin-danger-remove-unused-import'), { ignore: cannotRemoves }],
[require('babel-plugin-transform-define').default, constantsReplaceList]
]
}).ast as t.File
traverse(ast, {
ClassDeclaration (astPath) {
const node = astPath.node
let hasCreateData = false
if (node.superClass) {
astPath.traverse({
ClassMethod (astPath) {
if (astPath.get('key').isIdentifier({ name: '_createData' })) {
hasCreateData = true
}
}
})
if (hasCreateData) {
needExportDefault = true
astPath.traverse({
ClassMethod (astPath) {
const node = astPath.node
if (node.kind === 'constructor') {
astPath.traverse({
ExpressionStatement (astPath) {
const node = astPath.node
if (node.expression &&
node.expression.type === 'AssignmentExpression' &&
node.expression.operator === '=') {
const left = node.expression.left
if (left.type === 'MemberExpression' &&
left.object.type === 'ThisExpression' &&
left.property.type === 'Identifier' &&
left.property.name === 'config') {
configObj = traverseObjectNode(node.expression.right, buildAdapter)
}
}
}
})
}
}
})
if (node.id === null) {
componentClassName = '_TaroComponentClass'
astPath.replaceWith(
t.classDeclaration(
t.identifier(componentClassName),
node.superClass as t.Expression,
node.body as t.ClassBody,
node.decorators as t.Decorator[] || []
)
)
} else if (node.id.name === 'App') {
componentClassName = '_App'
//.........这里部分代码省略.........
示例8: recursiveRequire
async function recursiveRequire ({
filePath,
files,
isProduction,
npmConfig,
buildAdapter,
npmOutputDir,
rootNpm,
compileInclude = [],
env,
uglify,
babelConfig
}: {
filePath: string,
files: string[],
isProduction: boolean,
npmConfig: INpmConfig,
buildAdapter: BUILD_TYPES,
rootNpm: string,
npmOutputDir: string,
compileInclude: string[],
env: object,
uglify: TogglableOptions,
babelConfig: object
}) {
let fileContent = fs.readFileSync(filePath).toString()
let outputNpmPath = filePath.replace(rootNpm, npmOutputDir).replace(/node_modules/g, npmConfig.name)
if (buildAdapter === BUILD_TYPES.ALIPAY) {
outputNpmPath = outputNpmPath.replace(/@/g, '_')
}
if (REG_STYLE.test(path.basename(filePath))) {
return
}
fileContent = npmCodeHack(filePath, fileContent, buildAdapter)
try {
const constantsReplaceList = Object.assign({
'process.env.TARO_ENV': buildAdapter
}, generateEnvList(env || {}))
const transformResult = wxTransformer({
code: fileContent,
sourcePath: filePath,
outputPath: outputNpmPath,
isNormal: true,
adapter: buildAdapter,
isTyped: REG_TYPESCRIPT.test(filePath),
env: constantsReplaceList
})
const ast = babel.transformFromAst(transformResult.ast, '', {
plugins: [
[require('babel-plugin-transform-define').default, constantsReplaceList]
]
}).ast as t.File
fileContent = parseAst({
ast,
filePath,
files,
isProduction,
npmConfig,
rootNpm,
buildAdapter,
compileInclude,
npmOutputDir,
env,
uglify,
babelConfig
})
} catch (err) {
console.log(err)
}
if (!copyedFiles[outputNpmPath]) {
if (compileInclude && compileInclude.length) {
const filePathArr = filePath.split(path.sep)
const nodeModulesIndex = filePathArr.indexOf('node_modules')
const npmPkgName = filePathArr[nodeModulesIndex + 1]
if (compileInclude.indexOf(npmPkgName) >= 0) {
const compileScriptRes = await npmProcess.callPlugin('babel', fileContent, filePath, babelConfig, rootNpm)
fileContent = compileScriptRes.code
}
}
if (isProduction && buildAdapter !== BUILD_TYPES.QUICKAPP) {
const uglifyPluginConfig = uglify || { enable: true }
if (uglifyPluginConfig.enable) {
const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {})
const uglifyResult = npmProcess.callPluginSync('uglifyjs', fileContent, outputNpmPath, uglifyConfig, rootNpm)
if (uglifyResult.error) {
printLog(processTypeEnum.ERROR, '压缩错误', `文件${filePath}`)
console.log(uglifyResult.error)
} else {
fileContent = uglifyResult.code
}
}
}
fs.ensureDirSync(path.dirname(outputNpmPath))
fs.writeFileSync(outputNpmPath, fileContent)
let modifyOutput = outputNpmPath.replace(path.dirname(rootNpm) + path.sep, '')
modifyOutput = modifyOutput.split(path.sep).join('/')
printLog(processTypeEnum.COPY, 'NPM文件', modifyOutput)
copyedFiles[outputNpmPath] = true
}
}
示例9: parseJSCode
//.........这里部分代码省略.........
}
if (isEntryFile) {
// 注入 import page from 'XXX'
pages.forEach(item => {
const pagePath = item.startsWith('/') ? item : `/${item}`
const screenName = _.camelCase(pagePath)
const importScreen = template(
`import ${screenName} from '.${pagePath}'`,
babylonConfig as any
)()
node.body.unshift(importScreen as any)
})
// import tabBar icon
iconPaths.forEach(item => {
const iconPath = item.startsWith('/') ? item : `/${item}`
const iconName = _.camelCase(iconPath)
const importIcon = template(
`import ${iconName} from '.${iconPath}'`,
babylonConfig as any
)()
node.body.unshift(importIcon as any)
})
// Taro.initRouter 生成 RootStack
const routerPages = pages
.map(item => {
const pagePath = item.startsWith('/') ? item : `/${item}`
const screenName = _.camelCase(pagePath)
return `['${item}',${screenName}]`
})
.join(',')
node.body.push(template(
`const RootStack = ${routerImportDefaultName}.initRouter(
[${routerPages}],
${taroImportDefaultName},
App.config
)`,
babylonConfig as any
)() as any)
// initNativeApi
const initNativeApi = template(
`${taroImportDefaultName}.initNativeApi(${taroImportDefaultName})`,
babylonConfig as any
)()
node.body.push(initNativeApi as any)
// import @tarojs/taro-router-rn
const importTaroRouter = template(
`import TaroRouter from '${PACKAGES['@tarojs/taro-router-rn']}'`,
babylonConfig as any
)()
node.body.unshift(importTaroRouter as any)
// 根节点嵌套组件提供的 provider
const importTCRNProvider = template(
`import { Provider as ${taroComponentsRNProviderName} } from '${PACKAGES['@tarojs/components-rn']}'`,
babylonConfig
)()
node.body.unshift(importTCRNProvider)
// Taro.initPxTransform
node.body.push(getInitPxTransformNode(projectConfig) as any)
// export default App
if (!hasAppExportDefault) {
const appExportDefault = template(
`export default ${componentClassName}`,
babylonConfig as any
)()
node.body.push(appExportDefault as any)
}
}
}
}
})
try {
const constantsReplaceList = Object.assign({
'process.env.TARO_ENV': BUILD_TYPES.RN
}, Util.generateEnvList(projectConfig.env || {}), Util.generateConstantsList(projectConfig.defineConstants || {}))
// TODO 使用 babel-plugin-transform-jsx-to-stylesheet 处理 JSX 里面样式的处理,删除无效的样式引入待优化
ast = babel.transformFromAst(ast, code, {
plugins: [
[require('babel-plugin-transform-jsx-to-stylesheet'), {filePath}],
require('babel-plugin-transform-decorators-legacy').default,
require('babel-plugin-transform-class-properties'),
[require('babel-plugin-danger-remove-unused-import'), {ignore: ['@tarojs/taro', 'react', 'react-native', 'nervjs']}],
[require('babel-plugin-transform-define').default, constantsReplaceList]
]
}).ast
} catch (e) {
throw e
}
return {
code: unescape(generate(ast).code.replace(/\\u/g, '%u')),
styleFiles
}
}