If you utilize that particular syntax, it won't work as intended. However, there is a solution using dynamic imports that can achieve the desired outcome.
For more detailed examples and explanations regarding dynamic imports in TypeScript, you can visit .
In your specific scenario, the implementation would resemble the following:
const config = import('config').catch((error) => {
// Handle errors here
});
It is important to note that this approach introduces asynchronous loading, meaning that config
will represent a promise for the module value rather than the actual value itself. Consequently, the rest of your code will not automatically wait for the loading process to finish. You must explicitly use await config
wherever its value is needed.
The reason the standard import syntax does not suffice is because it is designed to be extracted and executed statically before any code execution occurs, leaving no room for error handling setup.
Upon the release of TypeScript 3.7, you will have the option to employ top-level await in modules, enabling config
to be treated as a conventional module value that subsequent code will naturally wait for:
const config = await import('config').catch((error) => {
// Handle errors here
});
As a final alternative, if you are utilizing commonjs modules, you can resort to a synchronous require('config')
call:
let config: any;
try {
config = require('config');
} catch (e) {
// Handle errors here
}
While this method delivers the expected outcome, it comes at the cost of type inference. It is advisable to transition towards ES modules rather than trying to work against them, given their standardized nature.