我想像ts-node这样在node.js中执行打字稿,然后导出模块默认项,并使用ts-node中的寄存器编译器通过代码加上
来实现var ts = require('typescript')
var fs = require('fs')
var Script = require('vm').Script
var register = require('ts-node').register
var DEFAULTS = require('ts-node').DEFAULTS
var diffLines = require('diff').diffLines
let EVAL_INSTANCE = { input: '', output: '', version: 0, lines: 0
}
const compilerOptions = {
allowJs: true
}
let dirName = '../../app/i18n/locales/ja'
let fileName = 'index.ts'
let path = `${dirName}/${fileName}`
let code = `export {default} from '${dirName}'`
let service = register({...DEFAULTS,compilerOptions})
const cwd = process.cwd()
let EVAL_FILENAME = `[eval].ts`
let EVAL_PATH = `${cwd}/${EVAL_FILENAME}`
global.__filename = EVAL_FILENAME
global.__dirname = cwd
global.exports = module.exports
global.module = module
global.require = module.require.bind(module)
let output = service.compile(code, EVAL_PATH, 0)
let result = exec(output)
console.log(result)
function exec (code , filename ) {
const script = new Script(code, { filename: filename })
return script.runInThisContext()
}
它们在我想要的控制台中显示输出,并将其放在下面的模块中。
import {Script} from 'vm'
import {DEFAULTS,register} from 'ts-node'
const compilerOptions = {
allowJs: true
}
let service = register({...DEFAULTS,compilerOptions})
const cwd = process.cwd()
let EVAL_FILENAME = `[eval].ts`
let EVAL_PATH = `${cwd}/${EVAL_FILENAME}`
;(global as any).__filename = EVAL_FILENAME
;(global as any).__dirname = cwd
;(global as any).exports = module.exports
;(global as any).module = module
;(global as any).require = module.require.bind(module)
export function tsTransform(filePath:string) {
let code = `export {default} from '${filePath}'`
let output = service.compile(code,EVAL_PATH,0)
return exec(output,EVAL_FILENAME)
}
function exec (code:string , filename:string ) {
const script = new Script(code, { filename: filename })
return script.runInThisContext()
}
和console.log(transform(absPath))可以很好地批量工作, 但是我开玩笑,测试失败了
src/lib/__tests__/tsTransformTest.ts
● tsTransform › retun appropriate Json › returns empty array
[eval].ts:2
Object.defineProperty(exports, "__esModule", { value: true });
^
ReferenceError: exports is not defined
用commonjs格式重写它们require和module.export,但是也一样。我不了解节点和开玩笑的运行环境的vm,所以我不知道为什么会这样。如果您知道原因,请帮助我。我想知道