'TypeScript + Angular dynamic Imports module build failed
I am working on a public personal project : https://github.com/chdelucia/hack
I would like to import some modules dynacmically. When I code it in a plain string is working as expected:
const a = await import(`../data/ctfbanditi`);
But when I try it with variables like this:
let b = 'ctfbanditi';
const a = await import(`../data/${b}`);
I get the following error:
Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: C:\MYlocalpath\data\ctfbanditi.ts is missing from the TypeScript compilation.
Please make sure it is in your tsconfig via the 'files' or 'include' property. at ivy\loader.js
I have read some similar issues were caused by miss spelling errors like lowercase uppercase and so on, but I think is no my case.
The idea is to have some function where got a name attribute and read the specific module like that:
async getBlogHtmlbyId(name: string): Promise<string> {
let code= '';
const a = await import(`../data/${name}`);
return code;
}
Any suggestions? Thanks in advance.
Solution 1:[1]
The solution for this problem is adding the ts modules on tsconfig.app.json
In my case all my modules i want to import dynacmically are stored on a folder /data/. So i added "src/data/*.ts" on include section like this:
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts",
],
"include": [
"src/**/*.d.ts",
"src/data/*.ts"
]
}
And on the service side:
async getBlogHtmlbyId(fileName: string): Promise<string> {
const code = await import(`../data/${fileName}`);
return code?.blog || '';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christian |
