首页 > 解决方案 > 使用 firebase 函数的共享模块和打字稿别名

问题描述

我无法让我的共享打字稿库使用带有 Firebase 函数的别名路径工作。

如果我使用相对路径引用它,则代码会编译,但我的functions/目录会上传到 Firebase Functions 并且不能使用其目录之外的相对文件。

目录结构

functions/
- tsconfig.json
- src/*.ts
- lib/*.js

shared/
- tsconfig.json
- src/*.ts
- lib/*.ts

src/
- components/*.vue

tsconfig.json
tsconfig-base.json

在我的函数文件中,我尝试引用我的一个共享模块,如下所示:

import { MyClass } from '@shared/src/MyClass'; // Error: Cannot find module '@shared/src/MyClass'

import { MyClass } from '../../shared/src/MyClass' // This Compiles, but fails deploying Cloud Functions

因为 Cloud Functions 需要在functions目录中拥有所有依赖项,所以我无法部署这些函数,即使它们都使用相对路径进行编译。

我的设置、结构或部署有什么问题?

我也尝试过"@shared": "file:../shared"按照functions/package.json此处所述添加

tsconfig-base.json

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "sourceMap": true,
        "strict": true,
        "declaration": true,
        "declarationMap": true,
        "lib": [
            "es2018"
        ],
        "target": "es2018",
        "types": [
            "node"
        ]
    },
    "compileOnSave": true,
    "files": [],
    "include": [],
    "exclude": [
        "lib",
        "node_modules"
    ]
}

共享/tsconfig.json

{
  "extends": "../tsconfig-base.json",
  "compilerOptions": {
    "composite": true,
    "baseUrl": "./",
    "outDir": "./lib",
    "rootDir": "./src",
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
  "references": [],
  "exclude": [
    "lib",
    "node_modules"
  ]
}

函数/tsconfig.json

{
  "extends": "../tsconfig-base.json",
  "references": [
    {
      "path": "../shared"
    }
  ],
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./lib",
    "rootDir": "./src",
    "paths": {
      "@shared/*": [
        "../shared/*"
      ]
    }
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
  "exclude": [
    "lib",
    "node_modules"
  ]
}

标签: javascripttypescriptfirebasegoogle-cloud-functions

解决方案


对于任何感兴趣的人,我目前的解决方法是使用 webpack(或vue.config.js在我的情况下)将共享文件复制到functions目录中,然后添加functions/shared到我的.gitignore.

不是最好的方法,但它有效。


推荐阅读