cancel
Showing results for 
Search instead for 
Did you mean: 

CDS Serve - Paths

mvoros
Active Contributor

Hi,

I have a CAP app that is written in TS. As the code growths, the import paths started to be really long as it would be something like import { Service} from ../../../../module/service. I looked for a solution for this and there seems to be an option for TS to define paths. This is what I have in tsconfig.js.

"baseUrl": "./",
"paths": {
"@/*": [
"*"
]
},

This allows me to have absolute import parts like this.

import * as pp from "@/srv/model/rsag.pp";

This seems to work OK for VSCode and tsc. VSCode code navigation works with this, I can Ctrl+click on the path and it opens the correct file. I can also run tsc and it correctly compiles the whole project. The problem is that when I am running cds-ts serve or cds serve in the build folder, it fails on the following error:

[ERROR] Cannot find module '@/srv/module/service'.

As an alternative, I tried also absolute path "srv/moule/service" but with the same result, tsc and VSCode are happy, cds not.

Is this supported? How can I make this work as it makes import statements easier to read.

Thanks

Accepted Solutions (1)

Accepted Solutions (1)

mvoros
Active Contributor

OK. I managed to make this work so I will try to explain what is happening. The settings above work only for tsc and VSCode. The problem is that when you specify absolute path like srv/module/service node will try to find the file in node_modules folder. This is a well known issue/limitation in node world and there are couple of solutions for this. The one that I picked and seems to work is to programmatically add ./ as root folder. Hence in my server.ts script, I added the following two lines:

process.env.NODE_PATH = "./";
require("module").Module._initPaths();

This lets node know that it should also look in the root folder when resolving dependencies. After these two lines, I can simply do imports like

import { Service } from "srv/module/Service"

No other config is needed as VSCode and tsc automatically supports absolute paths. For jest, there is a setting that needs to be set.

modulePaths: ["<rootDir>/"]

With these 3 lines, it all seems to be working fine and import paths are definitely easier to read.

Answers (0)