Home > other >  How to import data from a .env file in TypeScript project?
How to import data from a .env file in TypeScript project?

Time:08-30

I want to build sanity studio (sanity.io), in the studio root folder, there is a file, that is sanity.config.ts which is:

import {createConfig} from 'sanity';
import {deskTool} from 'sanity/desk';
import {schemaTypes} from './schemas';
import { markdownSchema } from 'sanity-plugin-markdown';

export default createConfig({
  name: 'default',
  title: 'dev-portfolio',

  projectId: 'lda05mbj',
  dataset: 'production',

  plugins: [deskTool(), markdownSchema()],

  schema: {
    types: schemaTypes,
  },
})

I want to import the projectId & dataset from a .env file, how I can do that? I create a .env file that is:

SANITY_PROJECT_ID=lda05mbj
SANITY_DATASET=production

Please help me!

CodePudding user response:

You have to prefix your environment variables with SANITY_STUDIO_ else it won't be included in the javaScript bundle. https://www.sanity.io/docs/studio-environment-variables#f5e9e3158896

CodePudding user response:

You have to install dotenv package using npm install dotenv. Then you have to load dotenv package in your project file using import 'dotenv/config'. Then you can access env constant in your project file using process.env.SANITY_PROJECT_ID and process.env.SANITY_DATASET.

  • Related