您可以在预加载文件(或任何文件)中使用 TypeScript。只需导入 ts-node 包并在导入任何 TypeScript 代码之前对其进行配置。
例如,制作一个 index.js 文件,其中包含:
require('./require-hooks')
module.exports = require('./entry') // this is your TypeScript entry point.
然后在您的 require-hooks.js 文件中配置 ts-node(ts-node 是一个即时编译 TypeScript 的 require 挂钩,并为后续运行提供缓存):
// ability to require/import TypeScript files
require('ts-node').register({
typeCheck: false, // faster, no type checking when require'ing files. Use another process to do actual type checking.
transpileOnly: true, // no type checking, just strip types and output JS.
files: true,
// manually supply our own compilerOptions, otherwise if we run this file
// from another project's location then ts-node will use
// the compilerOptions from that other location, which may not work.
compilerOptions: require('./tsconfig.json').compilerOptions,
})
注意,您可以在其中放置各种 require 挂钩,例如,您可以执行 require('path/to/file.ts')、require('path/to/file.tsx')、require('path/to/file.jsx')、require('path/to/file.png')、require('path/to/file.mp3') 等操作,您可以在其中定义用于处理某些类型文件的钩子(在某些方面类似于 Webpack,但挂钩到 Node 的内置 require 函数)。例如,@babel/register 是通过 Babel 运行 JS 文件的钩子,asset-require-hook 是允许您导入 JPG 文件等资产的 require 钩子,yaml-hook 允许您导入 require .yaml 文件。编辑:更多:css-modules-require-hook 用于导入 CSS 模块,module-alias 用于创建别名,如使用 WebPack。
pirates lib 是一种流行的工具,用于制作您自己的 require 钩子,尽管我也发现在没有库的情况下手动制作钩子很容易。例如,您可以覆盖 Module.prototype.require 来实现一些简单的钩子:
const path = require('path')
const url = require('url')
const Module = require('module')
const oldRequire = Module.prototype.require
function toFileURL(filePath) {
return url.format({
pathname: filePath,
protocol: 'file:',
slashes: true,
})
}
Module.prototype.require = function(moduleIdentifier) {
// this simple hook returns a `file://...` URL when you try to `require()`
// a file with extension obj, svg, png, or jpg.
if (['.obj', '.png', '.svg', '.jpg'].some(ext => moduleIdentifier.endsWith(ext))) {
const result = String(toFileURL(path.resolve(path.dirname(this.filename), moduleIdentifier)))
result.default = result
return result
} else {
return oldRequire.call(this, moduleIdentifier)
}
}
然后在其他文件中,
const fs = require('fs')
const img = require('path/to/foo.jpg')
console.log(img) // file:///absolute/path/to/foo.jpg
document.createElement('img').src = img
您甚至可以将对document.createElement('img').src = img 的调用移动到覆盖的require 方法中以自动执行此操作并返回img 元素而不是返回file:// URL。 :)
最后,在上述index.js 文件导入的./entry.ts 文件中,您可以在其中包含任何TypeScript。