背景
node版本的luckysheet之前是使用mjs的方式使代码支持esm,现在主管希望将mjs改回js,并且项目能正常运行。之后再将新功能合并到这个node版本中。
看了下代码,发现不光有mjs文件,项目中还有js文件并且用的是cjs。
如果将package.json中的type设为module,整个项目就只能使用esm,那就需要改js文件中的cjs(并且主管之前交代过这样改了之后有个库就用不了,哈?不懂。),不想改代码就需要想其他办法。
最终的办法是将src中的mjs文件后缀改为js,并且代码中的引用后缀也改掉,最后将代码用babel转化为cjs语法。
步骤
1、通过node脚本改文件后缀与文件引用【注意备份src文件夹!】
脚本是让ai写的,用node执行这两个脚本。【注意备份!!!】
1、修改src下所有.mjs文件后缀为.js
const fs = require('fs');
const path = require('path');
function renameFiles(directoryPath) {
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('无法读取目录:', err);
return;
}
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('无法获取文件信息:', err);
return;
}
if (stats.isDirectory()) {
// 如果是目录,则递归调用renameFiles函数
renameFiles(filePath);
} else if (path.extname(filePath) === '.mjs') {
// 如果是.mjs文件,则重命名为.js文件
const newFilePath = path.join(directoryPath, path.basename(file, '.mjs') + '.js');
fs.rename(filePath, newFilePath, (err) => {
if (err) {
console.error('无法重命名文件:', err);
} else {
console.log(`已将文件 ${file} 重命名为 ${path.basename(file, '.mjs') + '.js'}`);
}
});
}
});
});
});
}
const directoryPath = './src'; // 指定目录路径
renameFiles(directoryPath);
2、将.js文件中的 .mjs替换为.js
const fs = require('fs');
const path = require('path');
function replaceExtension(filePath) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('无法读取文件:', err);
return;
}
const updatedData = data.replace(/\.mjs/g, '.js');
fs.writeFile(filePath, updatedData, 'utf8', (err) => {
if (err) {
console.error('无法写入文件:', err);
} else {
console.log(`已将文件 ${filePath} 中的 .mjs 替换为 .js`);
}
});
});
}
function traverseDirectory(directoryPath) {
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('无法读取目录:', err);
return;
}
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('无法获取文件信息:', err);
return;
}
if (stats.isDirectory()) {
// 如果是目录,则递归调用traverseDirectory函数
traverseDirectory(filePath);
} else if (path.extname(filePath) === '.js') {
// 如果是.js文件,则替换文件中的.mjs为.js
replaceExtension(filePath);
}
});
});
});
}
const directoryPath = './src'; // 指定目录路径
traverseDirectory(directoryPath);
2、安装babel处理src下代码,将esm转为cjs
1、安装babel及其插件预设
npm install @babel/core @babel/cli @babel/preset-env
2、创建.babelrc文件,进行预设的配置
{
"presets": ["@babel/preset-env"]
}
3、再执行命令,用babel进行转化【可以将这段命令作为脚本写在package.json中】
npx babel src --out-dir dist
4、执行完命令后,就去使用dist下的代码就行了。启动项目调试运行,正常,结束。
总结
请教小伙伴们有没有更好的办法 。