Why is this error showing when trying to import a constant from another file in typescript?

Advertisements

I am trying to import a constant which is a JSON body from a file inside another folder inside my project.
I have tried copying the relative path to it and the constant has the export keyword before the declaration so I have export constant = {}

In the main file I am getting the Cannot find module error and I am running out of ideas as I have tried looking on google for possible fixes.

The files skeleton


**The import statement: **

import {post_next_questions_request_body} from '..post-calls-bodies/post-next-questions'; 

The error:

Cannot find module '..post-calls-bodies/post-next-questions' or its corresponding type declarations.

I have tried the following paths:
‘..post-calls-bodies/post-next-questions’
‘.post-calls-bodies/post-next-questions’
‘post-calls-bodies/post-next-questions’

with no success

>Solution :

You didn’t specified clearly which file you’re writing the import statement in – I’m going to assume you’re writing your import in next-questions-api-tests. I know I sound pedantic, but providing that level of textual explanation would make it easier for people to answer, since I had to open a picture in another tab to understand your question. Blind people cannot see that picture, and all of us can’t copy and paste text from it.

Anyway, you’re syntax for relative paths is wrong (you need a slash after .. or ., as in ../rest/of/the/path and ./rest/of/the/path).

Also, if my initial assumptions are right, the path itself is wrong: you need to go up two levels. Moving up once will put you in tests folder (just outside API Tests folder). Moving up once more will allow you then to go down inside post-call-bodies. In the end, you need:

import { post_next_questions_request_body } from '../../post-call-bodies/post-next-questions';

P.S.: If you don’t have a good reason, calling a folder API Tests is not the best in my experience. What bothers me is the whitespace. It’s a source of trouble in so many scripts and programs that if you don’t really need it, something like APITests or (even better) api_tests would be more robust.

Leave a ReplyCancel reply