在.mjs模块中直接引入package.json文件并使用其中的version变量,可以使用以下步骤:
-
导入
fs和path模块:由于.mjs是ES模块格式,你需要使用import语句来导入Node.js的内置模块fs(文件系统)和path(路径处理)来读取文件。 -
读取
package.json文件:使用fs.promises.readFile异步读取package.json文件内容,然后解析JSON字符串得到对象。
下面是一个示例代码:
import { readFile } from 'fs/promises';
import path from 'path';
async function getVersionFromPackageJson() {
try {
const filePath = path.resolve(__dirname, 'package.json');
const data = await readFile(filePath, 'utf8');
const packageJson = JSON.parse(data);
return packageJson.version;
} catch (error) {
console.error('Error reading package.json:', error);
return null;
}
}
getVersionFromPackageJson().then(version => {
if (version) {
console.log(`Current version: ${version}`);
}
});
这段代码首先定义了一个异步函数getVersionFromPackageJson,它读取当前目录下的package.json文件,将其内容解析成一个JavaScript对象,并返回version字段的值。然后,调用这个函数并打印出版本号。
请注意,由于.mjs文件在Node.js中的使用涉及到模块系统的不同处理,确保你的Node.js环境支持ES模块,并且在执行脚本时正确使用node --experimental-modules yourfile.mjs或者在Node.js项目根目录下有正确的"type": "module"配置在package.json中。

1万+

被折叠的 条评论
为什么被折叠?



