这是由于i18next-fs-backend使用了CommonJS语法,在ES模块中使用会出现问题。可以使用resolve这个包来解决这个问题,具体操作如下:
- 安装resolve
npm install resolve --save
- 在代码中引入resolve
import resolve from 'resolve';
- 替换CommonJS语法
// const path = require('path');
const path = new URL('path', file://${resolve.sync('path')}
).pathname;
// const fs = require('fs');
const fs = new Proxy({}, {
get: (_, prop) => {
if (prop === 'readFileSync') {
return (filePath) => {
try {
const fileUrl = new URL(filePath, file://${resolve.sync('.')}/
);
return fs.readFileSync(fileUrl);
} catch {
throw new Error(Cannot read file: ${filePath}
);
}
};
}
throw new Error(fs.${prop} is not implemented
);
},
});
// const importPath = require.resolve(path.join(localePath, namespace));
const importPath = new URL(namespace, file://${resolve.sync(localePath)}/
).pathname;
通过使用resolve包,我们可以将CommonJS语法替换为ES模块语法,从而解决这个错误。