Question
I’m currently working on a React app where I manage some JavaScript code that utilizes the require
function to import a TypeScript library. The import statement looks like this:
const timeZonePlugin = require('dayjs/plugin/utc');
This approach has been functioning well in production. In the TypeScript library, the export statement within the dayjs/plugin/utc.d.ts
file is:
import { PluginFunc, ConfigType } from 'dayjs';
declare const timeZonePlugin: PluginFunc;
export = timeZonePlugin;
From my understanding, the TypeScript export line:
export = timeZonePlugin;
corresponds to the JavaScript equivalent:
module.exports = timeZonePlugin;
Thus, the require(...)
function should provide the value of module.exports
. This led me to believe that:
const timeZonePlugin = require('dayjs/plugin/utc');
would bind timeZonePlugin
to what’s exported by the imported file.
I would like to know how I can achieve the same binding using the import
statement. Some resources mention that module.exports = ...
is similar to export default ...
. Hence, I tried:
import timeZonePlugin from 'dayjs/plugin/utc.d.ts';
But I encountered a compilation issue:
"default" is not exported by "node_modules/dayjs/plugin/utc.d.ts"
Indicating that module.exports = ...
might not equate to export default ...
. As an alternative, I attempted:
import * as timeZonePlugin from 'dayjs/plugin/utc.d.ts';
This time, there was no compile-time error. However, running the application resulted in a runtime issue:
Uncaught (in promise) ReferenceError: timeZonePlugin is not defined
It seems the import
is still not working as the original require()
method. After a full day of trying to resolve this, I’m out of ideas. Can anyone suggest how to correctly write an import statement that functions identically to the original require()
call?