Independent Development
Cannot find module in a project with TypeScript and JavaScript
Error
Working on such a project that has both TypeScript codes and JavaScript codes.
While compiling, the TypeScript codes will be translated into JavaScript codes, and the JavaScript codes will be copied directly.
It works well, but somehow it keeps giving errors like cannot find module.
The module was imported by TypeScript, but after tsc, the JavaScript code can not run.
Solution
Not quite sure about it, but it is something about TypeScript / CommonJS / ES6.
My JavaScript codes are ES6 / ESM. The compiling of TypeScript fits not very well with ESM.
If I am using CommonJS, everything should be fine.
But using ESM, the import must be with .js like this:
Import MyModule from `./my_module.js’;
And the result of TypeScript compiling do not always contains .js. That is the reason.
Finally, I use a script to scan all the files generated and add the .js one by one.
function fixImportPaths(dir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
fixImportPaths(filePath);
} else if (file.endsWith('.js')) {
let content = fs.readFileSync(filePath, 'utf8');
// Fix relative imports to add .js extension
content = content.replace(
/from ['"](\.\.?\/[^'"]*?)['"]/g,
(match, importPath) => {
if (!importPath.endsWith('.js')) {
return `from '${importPath}.js'`;
}
return match;
}
);
fs.writeFileSync(filePath, content);
}
});
}
fixImportPaths('./dist');
AI got me this script. It do not feel good, but it works.
Main Site(Under building)
Related Platforms
(Github Issues) / (Notion) / (Blog)
Advertisement
(A website to optimize your resume and to boost your career: Nonpareil.me)
独立开发
在混用TypeScript和JavaScript的项目中提示找不到模块
问题
我的项目里同时有TypeScript和JavaScript代码。
编译的时候,TypeScript代码会被编译成JavaScript代码,JavaScript原样复制过去,最终一起运行。
本来还心运行,不过不知道为什么,突然就一直报错找不到模块。
这个模块是在TypeScript引入的,不过在tsc编译之后就有问题了。
解决方案
不是很确定具体原因,不过和TypeScript / CommonJS / ES6有关。
我的JavaScript代码使用了ES6 / ESM语法,而TypeScript的编译结果不太能够适配ESM。
如果我用了CommonJS可能就不会有问题。
在ESM语法中,import语句必须带有.js后缀:
Import MyModule from `./my_module.js’;
TypeScript编译出的JavaScript文件中,有的带这个后缀,有的不带。因此才报错。
结果是,我用一个脚本扫描所生成的文件,然后一个一个添加.js后缀。
function fixImportPaths(dir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
fixImportPaths(filePath);
} else if (file.endsWith('.js')) {
let content = fs.readFileSync(filePath, 'utf8');
// Fix relative imports to add .js extension
content = content.replace(
/from ['"](\.\.?\/[^'"]*?)['"]/g,
(match, importPath) => {
if (!importPath.endsWith('.js')) {
return `from '${importPath}.js'`;
}
return match;
}
);
fs.writeFileSync(filePath, content);
}
});
}
fixImportPaths('./dist');
AI帮我生成的脚本。这个解决方案感觉很不好,但是能运行,那就这样吧。
主站(建设中)
[Nonpareil Me]{https://nonpareil.me}
相关平台
(Github Issues) / (Notion) / (Blog)