awesome-cordova-plugins/scripts/build/transformers/imports.ts

70 lines
2.2 KiB
TypeScript
Raw Normal View History

2017-12-28 20:28:44 +08:00
import * as ts from 'typescript';
import { getMethodsForDecorator } from '../helpers';
function transformImports(file: ts.SourceFile, ctx: ts.TransformationContext, ngcBuild?: boolean) {
// remove angular imports
if (!ngcBuild) {
file.statements = (file.statements as any).filter((s: any) => !(s.kind === ts.SyntaxKind.ImportDeclaration && s.moduleSpecifier.text === '@angular/core'));
}
// find the @ionic-native/core import statement
const importStatement = (file.statements as any).find((s: any) => {
return s.kind === ts.SyntaxKind.ImportDeclaration && s.moduleSpecifier.text === '@ionic-native/core';
});
// we're only interested in files containing @ionic-native/core import statement
if (!importStatement) return file;
2018-03-23 17:57:54 +08:00
const decorators: string[] = [];
2017-12-28 20:28:44 +08:00
const decoratorRegex: RegExp = /@([a-zA-Z]+)\(/g;
2018-04-20 01:52:26 +08:00
const ignored: string [] = ['Plugin', 'Component', 'Injectable'];
const keep: string [] = ['getPromise', 'checkAvailability'];
2017-12-28 21:40:52 +08:00
2017-12-28 20:28:44 +08:00
let m;
while ((m = decoratorRegex.exec(file.text)) !== null) {
if (m.index === decoratorRegex.lastIndex) {
decoratorRegex.lastIndex++;
}
2017-12-28 21:40:52 +08:00
if (m && m[1] && decorators.indexOf(m[1]) === -1 && ignored.indexOf(m[1]) === -1) decorators.push(m[1]);
2017-12-28 20:28:44 +08:00
}
if (decorators.length) {
let methods = [];
decorators.forEach(d => methods = getMethodsForDecorator(d).concat(methods));
importStatement.importClause.namedBindings.elements = [
ts.createIdentifier('IonicNativePlugin'),
2018-04-20 01:52:26 +08:00
...methods.map(m => ts.createIdentifier(m)),
...importStatement.importClause.namedBindings.elements.filter(el => keep.indexOf(el.name.text) !== -1)
2017-12-28 20:28:44 +08:00
];
2018-04-10 03:18:30 +08:00
if (ngcBuild) {
importStatement.importClause.namedBindings.elements = importStatement.importClause.namedBindings.elements.map(
binding => {
2018-04-20 01:52:26 +08:00
if (binding.escapedText) {
binding.name = {
text: binding.escapedText
};
}
2018-04-10 03:18:30 +08:00
return binding;
}
);
}
2017-12-28 20:28:44 +08:00
}
return file;
}
export function importsTransformer(ngcBuild?: boolean) {
return (ctx: ts.TransformationContext) => {
return tsSourceFile => {
return transformImports(tsSourceFile, ctx, ngcBuild);
2018-03-23 17:57:54 +08:00
};
2017-12-28 20:28:44 +08:00
};
}