How to use the ts-morph.Project function in ts-morph

To help you get started, we’ve selected a few ts-morph examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github VilledeMontreal / workit / packages / workit-cli / src / command / create / task / index.ts View on Github external
async function processHandler(className, contentFile, isBpmn = false) {
  const camelCase = require('camelcase');
  const classNameWithMaj = camelCase(className, { pascalCase: true });
  const classNameSanitized = camelCase(className);
  const project = new Project({
    // Optionally specify compiler options, tsconfig.json, virtual file system, and more here.
    // If you initialize with a tsconfig.json, then it will automatically populate the project
    // with the associated source files.
    // Read more: https://dsherret.github.io/ts-morph/setup/
  });

  if (fs.existsSync(`${localPath}/src/tasks/${classNameSanitized}.ts`)) {
    return Promise.resolve();
  }

  fs.writeFileSync(
    `${localPath}/src/tasks/${classNameSanitized}.ts`,
    contentFile.toString().replace('[CLASSNAME]', classNameWithMaj)
  );
  // tslint:disable: no-console
  const filePath = path.resolve(`${localPath}/src/config/ioc.ts`);
github gregjacobs / js-to-ts-converter / src / create-ts-ast-project.ts View on Github external
export function createTsAstProject( directory: string, options: {
	indentationText?: IndentationText,
	includePatterns?: string[],
	excludePatterns?: string[]
} = {} ) {
	const tsAstProject = new Project( {
		manipulationSettings: {
			indentationText: options.indentationText || IndentationText.Tab
		}
	} );

	// Get all files, and then filter. Was using glob-all and passing all of the
	// globs to the utility, but it takes way too long on large projects because
	// it seems to read the file system multiple times - once for each pattern.
	let files = glob.sync( `${directory}/**/*.+(js|ts|jsx|tsx)`, {
		follow: true   // follow symlinks
	} );

	// First, filter out any path which includes node_modules. We don't want to
	// attempt to parse those as they may be ES5, and we also don't accidentally
	// want to write out into the node_modules folder
	const nodeModulesRegex = /[\\\/]node_modules[\\\/]/;
github anoaland / anoa-cli / src / generators / views / arrow-function-component-generator.ts View on Github external
async generate(args: CreateComponentArgs): Promise {
    const { naming } = this.context

    // processing
    const project = new Project()

    const { location, props, state } = args
    const name =
      args.kind === ViewKindEnum.component
        ? naming.component(args.name)
        : naming.screen(args.name)

    // build view file
    const viewPath = path.join(location, 'index.tsx')
    const viewFile = project.createSourceFile(viewPath)

    // build props as required
    const hasProps = props && props.length
    let propsName: string

    if (hasProps) {
github dsherret / ts-morph / packages / scripts / src / changeTypeScriptVersion.ts View on Github external
function setModuleSpecifierValue(value: string) {
    const project = new Project();
    const declarationFile = project.addSourceFileAtPath(path.join(__dirname, "../../common/lib/ts-morph-common.d.ts"));
    const jsFile = project.addSourceFileAtPath(path.join(__dirname, "../../common/dist/ts-morph-common.js"));

    for (const importDec of declarationFile.getImportDeclarations()) {
        const moduleSpecifierValue = importDec.getModuleSpecifierValue();
        if (moduleSpecifierValue.startsWith("typescript"))
            importDec.setModuleSpecifier(value);
    }

    const callExpr = jsFile.getVariableDeclarationOrThrow("ts").getInitializerIfKindOrThrow(SyntaxKind.CallExpression);
    (callExpr.getArguments()[0] as StringLiteral).setLiteralValue(value);

    [declarationFile, jsFile].forEach(s => s.saveSync());
}
github wireapp / wire-web-packages / packages / swaxios / src / parser / Builder.ts View on Github external
constructor(spec: Spec, outputDir: string, separateFiles?: boolean) {
    this.spec = spec;
    this.outputDir = outputDir;
    this.separateFiles = separateFiles;

    this.project = new Project({
      manipulationSettings: {
        indentationText: IndentationText.TwoSpaces,
        quoteKind: QuoteKind.Single,
      },
    });
    this.interfaces = this.buildInterfaces();
    this.classes = this.buildClasses();
    this.mainClass = this.buildMainClass();
  }
github mselerin / yang-schematics / src / utils / code-utils.ts View on Github external
static getSourceFile(file: string, content: string): SourceFile {
    const project = new Project({
      useVirtualFileSystem: true,
      manipulationSettings: {
        quoteKind: QuoteKind.Single
      }
    });

    project.createSourceFile(file, content);

    let sourceFile = project.getSourceFile(file);
    if (!sourceFile) {
      sourceFile = project.createSourceFile(file, content);
    }

    return sourceFile;
  }
github compodoc / compodoc / src-refactored / core / use-cases / parse-file.ts View on Github external
constructor() {
        this.project = new Project({
            compilerOptions: {
                target: ScriptTarget.ES5,
                module: ts.ModuleKind.CommonJS,
                allowJs: true
            }
        });
    }
github fuse-box / fuse-box / src / production / stages / preparationStage.ts View on Github external
function staticTransform(props: IStaticTransform) {
  const module = props.productionModule.module;
  if (module.isExecutable()) {
    props.ctx.log.info('source transform', module.getShortPath());
    const project = new Project();
    const sourcePath = 'MyClass.tsx';
    props.productionModule.file = project.createSourceFile(sourcePath, module.contents);
    performStaticTransformations({
      ctx: module.props.ctx,
      file: props.productionModule.file,
      fuseBoxPath: module.props.fuseBoxPath,
    });
  }
}
export function preparationStage(props: IProductionFlow) {
github aurelia / aurelia / tools / api-doc-generator / helpers / aurelia / aurelia-source-utils.ts View on Github external
export function getAureliaSources(tsconfig: string): SourceFileInfo {
    const project = new Project({
        tsConfigFilePath: tsconfig,
    });
    const sources = project
        .getSourceFiles()
        .filter(item => item.getFilePath().includes('src'))
        .filter(item => !item.getFilePath().includes('__tests__'))
        .filter(item => !item.getFilePath().includes('__e2e__'))
        .filter(item => !item.getFilePath().includes('node_modules'))
        .filter(item => !item.getFilePath().includes('dist'))
        .filter(item => !item.getFilePath().includes('examples'))
        .filter(item => !item.getFilePath().includes('aot/src/vm'))
        .filter(item => item.isDeclarationFile() === false);
    const extractor = new SourceFileExtractor();
    const result = extractor.extractAll(sources);
    return result;
}
github thorn0 / organize-imports-cli / cli.js View on Github external
projects[tsConfigFilePath] = {
          files: [sourceFile],
          project,
          detectNewLineKind
        };
        continue;
      }
    }

    const adHocProjectKey =
      "\0" + JSON.stringify({ ...manipulationSettings, detectNewLineKind });

    if (!projects[adHocProjectKey]) {
      projects[adHocProjectKey] = {
        files: [],
        project: new Project({
          manipulationSettings,
          compilerOptions: { allowJs: true }
        }),
        detectNewLineKind
      };
    }

    /** @type {SourceFile[]} */ (projects[adHocProjectKey].files).push(
      projects[adHocProjectKey].project.addSourceFileAtPath(filePath)
    );
  }

  for (const { files, project, detectNewLineKind } of Object.values(projects)) {
    const sourceFiles = files === "all" ? project.getSourceFiles() : files;
    const differentFiles = [];
    let crLfWeight = 0;