【发布时间】:2018-12-31 13:45:46
【问题描述】:
我正在尝试注入一个模块
Transformer.ts 的导入语句
(* 我使用了 ttypescript,它可以工作,
但有些陈述是未经解释的。)
我成功插入了导入语句
但是我注入的导入语句
没有间歇性地翻译成 es5 语法。
这是我在变压器中使用的代码。
transformer.ts
let moduleName = 'infinite.js'
let variableName = ts.createUniqueName('infinite')
ctx.hoistVariableDeclaration('infinite')
// Here are just a few key codes summarised.
let importInject = ts.createImportDeclaration(
undefined,
undefined,
ts.createImportClause(variableName, undefined),
ts.createLiteral(moduleName))
sourceFile = ts.updateSourceFileNode(sourceFile, ts.createNodeArray([
importInject,
...sourceFile.statements
]))
source.js
// Nothing before it.
source.js(注入导入语句)
import infinite_1 from"infinite.js"
代码注入工作正常,
虽然定义了 es5 的编译器目标选项,
但是我插入的代码存在无法翻译的问题。
但是,如果我添加一个导入语句
与模块导入代码无关
我会在模块注入之前注入源代码,
我插入的代码翻译也成功了。
source.js
import module from './module'
module()
source.js(注入导入语句)
"use strict";
exports.__esModule = true;
var infinite_js_1 = require("infinite.js");
var module_1 = require("./module");
module_1["default"]();
嗯...这是编译选项的问题...?
如果是,应该修改哪些编译选项?
我不知道要修改哪个代码...(x_x)
有没有人遇到过这样的问题?
如果您知道解决方案,请告诉我。
另外,我目前正在使用以下临时解决方案。
let importInject =
ts.createVariableStatement(
sourceFile.modifiers,
[ts.createVariableDeclaration(
variableName,
undefined, // Type
ts.createCall(
ts.createIdentifier('require'),
undefined,
[ts.createLiteral(moduleName)]
)
)]
)
【问题讨论】:
标签: typescript typescript-compiler-api