Search code examples
typescriptnestjs

Importing ts files in nestJs


I'm new to nestJs,

I have written one file called constants.ts

module.exports = {
    ROLES: {
        ADMIN: 'admin',
        LOCAL: 'local'
    }
}

This file I'm trying to import in another file with below code.

import * as constants from '../lib/constants'

But getting 'constants.ts' is not a module error.

Can anyone help me on this? Please.

And also please tell me how to import .json files.


Solution

  • It seems like you're trying to import a CommonJS module in a TypeScript module, which can cause issues. To fix this, you can try changing the module exports in your 'constants.ts' file to a TypeScript module format:

    export const ROLES = {
      ADMIN: 'admin',
      LOCAL: 'local'
    };
    

    And then in the file where you want to import it:

    import { ROLES } from '../lib/constants';
    

    Regarding importing JSON files, you can use the import statement as well. For example, if you have a file called config.json, you can import it like this:

    import config from './config.json';
    

    Keep in mind that if you're using TypeScript, you may need to define a type for the imported JSON data. You can do this by creating an interface for the JSON structure:

    interface Config {
      apiUrl: string;
      apiKey: string;
    }
    
    const config: Config = require('./config.json');