on 2023 Jan 25 3:18 PM
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
Request clarification before answering.
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
59 | |
7 | |
6 | |
6 | |
5 | |
5 | |
4 | |
4 | |
3 | |
3 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.