Node.js 如何将来自不同文件的所有导出合并到一个文件中?
e、 gNode.js 如何将来自不同文件的所有导出合并到一个文件中?,node.js,npm,node-modules,Node.js,Npm,Node Modules,e、 g 在一个文件夹中,比如说xyz我有两个文件名为*.const.js,还有一个index.js。我希望index.js中有一个自动代码,它合并*.const.js中的所有导出,假设您希望在启动时执行此操作: ./one.const.js ---------> module.exports = {}; ./two.const.js ----------> module.exports = {}; ./index.js---------------> module.expor
在一个文件夹中,比如说
xyz
我有两个文件名为*.const.js,还有一个index.js。我希望index.js中有一个自动代码,它合并*.const.js中的所有导出,假设您希望在启动时执行此操作:
./one.const.js ---------> module.exports = {};
./two.const.js ----------> module.exports = {};
./index.js---------------> module.exports = mergedExports; // mergedExports: {one: {}, two: {}};
const fs=require('fs');
const regex=new RegExp('.const.js$'))
const files=fs.readdirSync('.').filter((文件名)=>regex.test(文件名))
const mergedExports={};
for(设i=0;i
如果要将导出合并到单个对象中,请将for循环更新为:
const fs = require('fs');
const regex = new RegExp('.const.js$')
const files = fs.readdirSync('.').filter((fileName) => regex.test(fileName))
const mergedExports = {};
for (let i =0; i < files.length; i++) {
const fileName = files[i].split('.const.js')[0]
mergedExports[fileName] = require(`./${files[i]}`)
}
module.exports = mergedExports
for(设i=0;i
在一个文件夹中,比如说xyz
我有两个带有*.const.js文件名的文件,还有一个index.js
require()的默认行为是,如果不手动指定要导入的文件,它将在xyz文件夹中查找index.js
index.js
for (let i =0; i < files.length; i++) {
mergedExports = { ...mergedExports,
...require(`./${files[i]}`),
}
}
outside.js
exports.One = require("./one.const.js");
exports.Two = require("./two.const.js");
你为什么要这么做?这似乎与node.js模块化的目标背道而驰,它的工作方式很有魅力。但有一个问题是,最终导出的密钥名与文件名相同,即
mergedExports-->{“one.const.js”:{},“two.const.js”:{}代码>我们可以将其重命名为1和2吗?此脚本已经做到了这一点,请参见下面的行,其中显示const fileName=files[i].split('.const.js')[0]
哦,我很抱歉!我尝试使用不同的文件名。;-)还有一件事,如果我不需要任何键,只需将每个导出合并到一个对象中,该怎么办@阿尤什·古普塔
const { One, Two } = require("./xyz");