Typescript 未捕获类型错误:i18next.init不是函数
我在项目中使用typescript,在内部化中使用i18next 类型脚本:v2.1.4 i18next:v2.3.4 @类型/i18下一步:v2.3.35 在我的文件中:Typescript 未捕获类型错误:i18next.init不是函数,typescript,i18next,Typescript,I18next,我在项目中使用typescript,在内部化中使用i18next 类型脚本:v2.1.4 i18next:v2.3.4 @类型/i18下一步:v2.3.35 在我的文件中: import * as i18next from 'i18next'; i18next.init({ lng: 'en', resources: { en: { translation: { "key": "hello world"
import * as i18next from 'i18next';
i18next.init({
lng: 'en',
resources: {
en: {
translation: {
"key": "hello world"
}
}
}
}, (err, t) => {
// initialized and ready to go!
const hw = i18next.t('key'); // hw = 'hello world'
});
然而,在浏览器中,它说:
Uncaught TypeError: i18next.init is not a function
如果我记录i18next对象,它看起来像:
在控制台里
i18n.default.init
效果很好
如果像文件一样导入
import i18next from 'i18next';
在visual studio中,代码将投诉:
我的.tsconfig
{
"compileOnSave": true,
"compilerOptions": {
"removeComments": false,
"baseUrl": "./src",
"target": "es6",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noImplicitAny": true,
"strictNullChecks": true,
"jsx": "preserve",
"lib": [
"es2017",
"dom"
],
"typeRoots": [
"./node_modules/@types"
],
"types": [
"node",
"poly2tri",
"three",
"i18next"
]
}
}
我的webpack.config.js太长,无法阅读
我想知道是否与该文件有关:
你遇到的问题与 TypeScript和Babel/NodeJS中的模块解析语法不同 在Babel/NodeJS(最新草案)中,CommonJS模块使用以下语法导入:
import i18n from 'i18next'
i、 e.CommonJS模块移动到ES6模块的默认
导出
但是,TypeScript不遵循以下路线:
import * as i18n from 'i18next'
因此,当由tsc
编译到es6
时,此导入语句保持原样。
因此巴贝尔做了错事
请在上述问题上提高您的声音,以获得团队的更多关注
这个问题应该是一个问题,并尽快解决
目前,一种解决方案是通过tsc
将代码编译到es5;博士
在i18next
版本中,您必须以以下方式导入它:
import { default as i18n } from 'i18next';
在tsconfig.js
中设置“esModuleInterop”:true
以使其与jest
一起工作
我在tsconfig.js
中的其他模块选项(不确定是否需要所有这些选项才能使其正常工作):
解释
:
- 删除主文件中的命名导出-避免混合导出中的问题,提高commonjs场景(node.js)中的使用效率-无奇怪常量i18next=require('i18next')。默认值李>
- 影响您不能再从“i18next”导入{changeLanguage};变更语言(“de”);您必须从“i18next”导入i18next;i18next.changeLanguage(“de”)李>
如何在浏览器中运行代码?我(在NodeJS中)对它进行了测试,init函数在那里使用了
import*作为“i18next”中的i18next
我正在使用i18next@7.1.0
thouI正在使用webpack。因为@types/i18next是针对2.3.4的,所以我坚持使用这个版本。我用2.3.4进行了测试,它仍然有效。似乎您的设置有问题。你能发布你的tsconfig.json
和网页配置吗?
import { default as i18n } from 'i18next';
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"module": "es6",
"moduleResolution": "node",
"target": "es6",