I’m trying to load a variable from the .env
file inside my generate-keypair.ts
file. I’m using dotenv
to load the environment variables and esrun
to run the TypeScript file. Both my .env
file and TypeScript file are in the same directory.
But it keeps giving me this error:
node:internal/process/esm_loader:34
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:web3-solanagenerate-keypairnode_modules.binnode_modulesdotenvconfig.js' imported from F:web3-solanagen F:web3-solanagenerate-keypairnode_modules.binesrun-1723725354847.tmp.mjs
Did you mean to import "../dotenv/config.js"?
at finalizeResolution (node:internal/modules/esm/resolve:265:11)
at moduleResolve (node:internal/modules/esm/resolve:933:10)
at defaultResolve (node:internal/modules/esm/resolve:1157:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:390:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:359:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:234:38)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:87:39)
at link (node:internal/modules/esm/module_job:86:36) {
code: 'ERR_MODULE_NOT_FOUND',
url: 'file:///F:/web3-solana/generate-keypair/node_modules/.bin/node_modules/dotenv/config.js'
}
Node.js v20.12.1
Here’s my generate-keypair.ts
file:
import 'dotenv/config';
import {getKeypairFromEnvironment} from '@solana-developers/helpers';
console.log(process.env.SECRET_KEY);
const keypair = getKeypairFromEnvironment('SECRET_KEY');
console.log(`✅ Finished! We've loaded our secret key securely, using an env file!`);
When I comment the import "dotenv/config"
the code runs without error but gives undefined
for the process.env.SECRET_KEY
variable.
How can I read the exact value of the SECRET_KEY
variable from the .env
file instead of undefined?
1
Since you are using node.js, you probably have a typescript moduleResolution compiler option of node16
or nodenext
, so when you ES modules (import
) you have to specify the module path by adding .js
extension after file name, in your case you have to import like this: import 'dotenv/config.js'
.
If you read the error you should notice that the error provides the solution.