i18next: Mismatch between TypeScript types and CommonJS export
After disabling an ESLint rule that was causing me trouble, I ran into a new issue trying to incorporate i18next into my project.
I’m writing code for a back-end NodeJS server that is compiled with TypeScript. Therefore the import
syntax is handled not by Babel, but by TypeScript - and gets translated as such:
import i18next from "i18next";
// Becomes:
const i18next_1 = require("i18next").default;
This output JavaScript is then run in NodeJS like normal, relying on the main
key in the package.json
to locate the module. Thus it loads ./dist/cjs/i18next.js
, which exports like so:
//...
var i18next = new I18n();
module.exports = i18next;
As you can see, there’s no export called “default”. Therefore what I really need is to import the module.exports
under the name i18next. This can be done in TypeScript:
import * as i18next from "i18next";
However when I do this, I start getting errors whenever I try to use it:
Worse yet, since these are TypeScript errors and not ESLint errors, I can’t just hand-wave them or disable them. Attempting to run tsc
against my code stops compilation early with the error:
stevenbarnett@MacBook-Pro bf-hapijs-plugin % npx tsc
src/i18n/index.ts:33:35 - error TS2339: Property 'init' does not exist on type 'typeof import("/Users/stevenbarnett/Repos/pangolin-jerky/bf-hapijs-plugin/node_modules/i18next/index")'.
33 const translate = await i18next.init({
~~~~
Found 1 error.
For the record, if I don’t try to import i18next this way (using import * as ...
) then the following happens:
import i18next from "i18next";
console.log(i18next); // -> undefined
i18next.init(); // -> crashes with error "Cannot read property 'init' of undefined"
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 20 (12 by maintainers)
Commits related to this issue
- cjs export hack for TypeScript, could possibly fix #1447 — committed to i18next/i18next by adrai 4 years ago
Try to enable esModuleInterop.