【问题标题】:Using Typescript's baseUrl compiler option with node将 Typescript 的 baseUrl 编译器选项与节点一起使用
【发布时间】:2016-12-20 15:53:08
【问题描述】:

node的模块加载器能否支持TS的baseUrl编译选项?

TS 2 引入了baseUrl 编译器选项,以有效地启用项目相关的require()import 请求。

但是,这需要模块加载器支持同样的事情,因为 TS 在转译期间实际上并没有重写请求。对于像 webpack 这样的工具,这相当简单。

不幸的是,当使用 TS 开发 node 应用程序(即后端服务、命令行工具、电子桌面应用程序)时,似乎没有办法改变节点的模块加载器行为。

有办法吗?

【问题讨论】:

    标签: node.js typescript typescript2.0 compiler-options


    【解决方案1】:

    是的!

    感谢 TS 的立场,对于我们这些使用node,但希望使用baseUrl 相对于require() 调用的方便,这里有一个简单的解决方案。

    此解决方案挂钩noderequire() 调用,并使用“main”的dirname 解析请求以模仿baseUrl。因此,它假定 baseUrl 编译器选项也设置为源“main.ts”所在的同一目录。

    要使用,请将一小段代码粘贴到“main.ts”的顶部。

    import * as path from 'path'
    import * as fs from 'fs'
    (function() {
      const CH_PERIOD = 46
      const baseUrl = path.dirname(process['mainModule'].filename)
      const existsCache = {d:0}; delete existsCache.d
      const moduleProto = Object.getPrototypeOf(module)
      const origRequire = moduleProto.require
      moduleProto.require = function(request) {
        let existsPath = existsCache[request]
        if(existsPath === undefined) {
          existsPath = ''
          if(!path.isAbsolute(request) && request.charCodeAt(0) !== CH_PERIOD) {
            const ext = path.extname(request)
            const basedRequest = path.join(baseUrl, ext ? request : request + '.js')
            if(fs.existsSync(basedRequest)) existsPath = basedRequest
            else {
              const basedIndexRequest = path.join(baseUrl, request, 'index.js')
              existsPath = fs.existsSync(basedIndexRequest) ? basedIndexRequest : ''
            }
          }
          existsCache[request] = existsPath
        }
        return origRequire.call(this, existsPath || request)
      }
    })()
    

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2011-12-14
      • 1970-01-01
      • 2018-10-20
      • 2021-03-07
      • 2023-04-06
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多