Reputation: 5183
I am maintaining some Javascript code in a React application that imports from a Typescript library using the require
function.
The import statement looks like this:
const utc = require('dayjs/plugin/utc');
and has worked in production for quite some time.
The export statement in the Typescript module (file dayjs/plugin/utc.d.ts
) is
import { PluginFunc, ConfigType } from 'dayjs'
declare const plugin: PluginFunc
export = plugin
As far as I understand from the documentation, the Typescript statement
export = plugin
is equivalent to the Javascript statement
module.exports = plugin
Furthermore, require(...) should return the value of module.exports
. So, in the original code
const utc = require('dayjs/plugin/utc');
I would expect the constant utc
to be bound to the value of plugin
from the imported file.
So how can I bind utc
to the same value using import
? I found some hints in an answer to this question: module.exports = ...
should be equivalent to export default ...
. The comments to that answer suggest that the correct way to import would then be:
import utc from "dayjs/plugin/utc.d.ts";
thus binding utc
to module.exports
which is set to plugin
by the Typescript export statement.
Unfortunately, this produces a compilation error:
"default" is not exported by "node_modules/dayjs/plugin/utc.d.ts"
so, apparently, modules.exports = ...
is not equivalent to export default ...
.
By looking at another answer to the same question and at another question, I found the alternative syntax:
import * as utc from "dayjs/plugin/utc.d.ts";
I am not sure how the two differ, but this time the compiler did not complain. However, when I start the application, I get a runtime error:
Uncaught (in promise) ReferenceError: plugin is not defined
so, again, the semantics of my import
statement is not equivalent to that of the original solution using require()
: At runtime, something different happens. After spending one day on this, I am running out of ideas.
Do you have any ideas as to how to write an import statement that is 100% equivalent to the original code using require()
?
Upvotes: 0
Views: 29