typescript#ImportDeclaration TypeScript Examples

The following examples show how to use typescript#ImportDeclaration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: import-utils.ts    From jmix-frontend with Apache License 2.0 7 votes vote down vote up
export function createIncludes(importInfos: ImportInfo[], current?: ImportInfo): ts.ImportDeclaration[] {

  //todo do not add space between each include line

  //filter unique and exclude current entity, group by importPath
  const importByPathMap: Map<string, ImportInfo[]> = new Map();
  importInfos
    .filter(imp => !isImportEquals(imp, current))
    .forEach(imp => {
      const importByPath = importByPathMap.get(imp.importPath);
      if (importByPath) {
        if (!importByPath.some(i => isImportEquals(i, imp))) {
          importByPath.push(imp);
        }
      } else {
        importByPathMap.set(imp.importPath, [imp]);
      }
    });

  return [...importByPathMap.entries()]
    .map(([importPath, importInfos]) => {
      return importDeclaration(importInfos.map(ii => ii.className), importPath);
    });
}
Example #2
Source File: import-utils.ts    From jmix-frontend with Apache License 2.0 7 votes vote down vote up
export function importDeclaration(identifiers: string[], moduleSpec: string): ImportDeclaration {
  const elements = identifiers.map(idn =>
    ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(idn)));

    return ts.factory.createImportDeclaration(
      undefined,
      undefined,
      ts.factory.createImportClause(
        false,
        undefined,
        ts.factory.createNamedImports(elements)
      ),
      ts.factory.createStringLiteral(moduleSpec)
  );
}
Example #3
Source File: hooks-example.ts    From elephize with MIT License 5 votes vote down vote up
hooks: ElephizeNodeHookEntry[] = [
  {
    // nodeKind value should be one of typescript's SyntaxKind enum values.
    // It represents kind of node in the AST to apply hook to.
    nodeKind: SyntaxKind.NumericLiteral,

    // Here is the hook itself: a function called when typescript parser finds node of this kind.
    // Note: in general, hook is called TWICE: once for dry run, and once for code generation.
    hook: (
      // First argument of hook function is a node itself.
      // It's a good idea to cast the argument to type referred by SyntaxKind above.
      node: NumericLiteral,

      // Second argument is elephize compilation context.
      // It contains numerous settings and methods to use, see elephize's renderers code for details.
      context
    ) => {
      // Hook should return object having one of the following shapes:
      // { preventDefault: false } - to permit elephize make it's own magic on same node
      // { preventDefault: true, content: <SOME_STRING> } - to prevent elephize handling of the node and
      //   output <SOME_STRING> right in-place.

      if (context.dryRun) { // Simplest way to prevent executing hook code twice
        return { preventDefault: false };
      }

      // Simple example of additional code preprocessing
      if (node.getText().endsWith('.')) {
        return { preventDefault: true, content: `1 + ${node.getText()}` };
      } else {
        return { preventDefault: false };
      }
    },
  },
  {
    // Some node kinds can't be printed with 'content' property. All content will be ignored during code generation.
    // ImportDeclaration is one of such node kinds, but there are definitely more, especially statement-based kinds
    // can be affected with this. If your statement-based hook fails to output some code, this might be it.
    // We still can read and process those nodes though. For imports, we can read module specifiers and process
    // imported files in some different manner.
    nodeKind: SyntaxKind.ImportDeclaration,
    hook: (node: ImportDeclaration) => {
      if ((node.moduleSpecifier as StringLiteral).text.endsWith('.css')) {
        // Here we can do something with css import...
        return { preventDefault: true, content: '' };
      }
      return { preventDefault: false };
    },
  },
]
Example #4
Source File: addDenoExtensions.ts    From date-fns-jalali with MIT License 5 votes vote down vote up
globby('deno')
  .then((files) =>
    files.filter(
      (file) => pattern.test(file) && !ignore.find((p) => p.test(file))
    )
  )
  .then((files) =>
    Promise.all(
      files.map((file) =>
        readFile(file, 'utf8').then(async (content) => {
          const source = ts.createSourceFile(
            file,
            content,
            ts.ScriptTarget.Latest
          )
          const imports: string[] = []

          source.forEachChild((node) => {
            if (
              [
                ts.SyntaxKind.ImportDeclaration,
                ts.SyntaxKind.ExportDeclaration,
              ].includes(node.kind)
            ) {
              const importNode = node as ImportDeclaration | ExportDeclaration
              const specifier = importNode.moduleSpecifier as StringLiteral
              const importPath = specifier.text
              const isLocal = /\.\/.+/
              if (isLocal) imports.push(importPath)
            }
          })

          await Promise.all(
            imports.map(async (importPath) => {
              if (resolvedExtensions[importPath]) return
              const fullPath = resolveFullPath(file, importPath)
              let isTs = false
              try {
                await stat(fullPath + '.ts')
                isTs = true
              } catch (_) {}
              resolvedExtensions[fullPath] = isTs ? '.ts' : '.js'
            })
          )

          return writeFile(
            file,
            imports.reduce((acc, importPath) => {
              const fullPath = resolveFullPath(file, importPath)
              return acc.replace(
                new RegExp(importPath, 'g'),
                importPath + resolvedExtensions[fullPath]
              )
            }, content)
          )
        })
      )
    )
  )