首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使用typescript编译器API以编程方式生成import语句

使用typescript编译器API以编程方式生成import语句
EN

Stack Overflow用户
提问于 2020-01-11 19:07:53
回答 1查看 403关注 0票数 2

我想生成以下import语句:

代码语言:javascript
代码运行次数:0
运行
复制
import { Something } from 'a-module';

为此,我使用typescript compiler API

代码语言:javascript
代码运行次数:0
运行
复制
import * as ts from 'typescript';

const sourceFile = ts.createSourceFile(
    `source.ts`,
    ``,
    ts.ScriptTarget.Latest,
    false,
    ts.ScriptKind.TS
);

const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });

const importNode = ts.createImportDeclaration(
    /* decorators */ undefined,
    /* modifiers */ undefined,
    ts.createImportClause(
        ts.createIdentifier('Something'),
        /* namedBindings */ undefined
    ),
    ts.createLiteral('a-module')
);

const result = printer.printNode(ts.EmitHint.Unspecified, importNode, sourceFile);

console.log(result);
// prints --> import Something from "a-module";

如何将大括号语法添加到import语句中?可能与createImportClause中的namedBindings参数有关,但我不确定如何使用它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-11 19:44:36

Ok找到了(我猜一定是用了namedBindings):

代码语言:javascript
代码运行次数:0
运行
复制
// [...]

const importNode = ts.createImportDeclaration(
    /* decorators */ undefined,
    /* modifiers */ undefined,
    ts.createImportClause(
        undefined,
        ts.createNamedImports(
            [
                ts.createImportSpecifier(undefined, ts.createIdentifier('Something')),
            ]
        )
    ),
    ts.createLiteral('a-module')
);

// [...]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59693819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档