如何在 tsconfig.json 中包含 .env 文件以用于转译器

问题描述 投票:0回答:2

我有一个像这样的打字稿项目结构:

root/
  app/
    index.ts
  config/
    .env.dev

在index.ts内部,我想用指向

dotenv.config()
文件的路径调用
.env.dev
来配置它:

import * as dotenv from 'dotenv';
import path from 'path';

// set __dirname, yada yada yada
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// NODE_ENV is defined manually to NODE_ENV=dev
const dotenvPath = path.join(__dirname, '../', `config/.env.${process.env.NODE_ENV}`);
dotenv.config({
  path: dotenvPath,
});

console.log(`dotenvPath: ${dotenvPath}`)
console.log(`${process.env.SOMEVAR_INSIDE_ENVDEV_FILE}`) // <-- undefined

但是,当我尝试使用

process.env.SOMEVAR_INSIDE_ENVDEV_FILE
时,它是未定义的。

console.log(`dotenvPath: ${dotenvPath}`)
输出:

dotenvPath: C:\Users\myuser\path\to\project\.build\config\.env.dev

然而,

.build\config\
似乎不存在。这是我的
tsconfig.json
:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "outDir": "./build",
    "rootDir": "./app"
  },
  "exclude": ["node_modules"]
}

"exclude"
标签后添加以下标签:

"include": [
    "./config/*",
 ],

给了我一个奇怪的错误,我找不到太多相关信息:

Error: [{"messageText":"No inputs were found in config file 'tsconfig.json'. Specified 'include' paths were '[\"./config/*\"]' and 'exclude' paths were '[\"node_modules\"]'.","category":1,"code":18003}]
。我找到的唯一资源是this,但对我来说没有多大意义,因为我发现我所做的没有任何问题。

如何强制 TypeScript 将我的

./config/.env.dev
文件包含到转译过程中,以便我可以在运行时访问它?

typescript tsconfig
2个回答
1
投票

Typescript 仅转换 Typescript 文件和潜在的 Javascript 文件。如果您只想编写一个脚本来复制文件(如果文件已更改),那么对于采用像 Make 这样的构建工具来说,这似乎是一个很好的问题。


0
投票

只需在 npm 脚本中使用 cp 即可。 这是我的 package.json 中的脚本部分

"scripts": {
    "start:dev": "npx nodemon",
    "local": "env-cmd -f .env.local nodemon src/index.js",
    "local:test": "env-cmd -f .env.test nodemon src/index.js",
    "development": "env-cmd -f .env.development node src/index.js",
    "production": "env-cmd -f .env.production node src/index.js",
    "build": "rimraf ./build && mkdir build && tsc",
    "start": "npm run build && cp .env.local build/.env && node build/index.js",
    "test": "env-cmd -f .env.test mocha test/loging.test.js --exit"
},

关键命令是“npm run start” 1 - 删除旧版本 2 - 创建目录“build” 3 - 将 typescript 编译为 javascript 4 - 将当前的 .env.loca 复制到文件夹 build 并将其重新命名为 .env 5 - 执行您的应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.