As I work on converting my code from non-TypeScript CommonJS files to TypeScript ES6 modules, I encountered an issue with the import statements. Specifically, I needed to use import * as x
instead of import x
:
The original snippet looked like this:
const luxon = require('luxon');
console.log(luxon.DateTime.now().toString());
However, in my attempt to upgrade, I mistakenly altered it to:
import luxon from 'luxon';
console.log(luxon.DateTime.now().toString());
This change resulted in an error:
Cannot read property 'DateTime' of undefined
The root cause lies in luxon not having a default export. Thus, using import luxon from 'luxon'
actually translates to something like
const luxon = require('luxon').default;
.
To rectify this, the correct way to import is:
import * as luxon from 'luxon'; // or alternatively, import { DateTime } from 'luxon'
My inquiry is: why doesn't TypeScript alert me about utilizing a non-existent default export, and what can I do to prompt such detection? Interestingly, TypeScript does flag an erroneous default export usage within its own modules but seems lenient when dealing with JavaScript imports (even after including type definitions).