我有以下node.js代码,它们在多个.js文件中重复出现-

时间:2018-07-17 19:55:56

标签: node.js

const c1 = require('package1')
const c2 = require('package2')
const c3 = require('package3')
const c4 = require('package4')
const c5 = require('package5')
const c6 = require('package6')
const iodata;

function foo()
{
  let secretpath = "../abc/def/file.txt"
  let filedata = await readCredentialsFromFile(secretPath); 
  iodata = filedata[0]; // iodata initialized to be used in other files.
  return filedata;
}  

如何以在每个文件中只写一个 require 语句的方式重构它?

1 个答案:

答案 0 :(得分:1)

你是说这样吗?

commonDeps.js

exports.c1 = require("package1")
exports.c2 = require("package2")
exports.c3 = require("package3")

a.js

const cc = require("./commonDeps");
const c1 = cc.c1;

b.js

const c2 = require("./commonDeps").c2;

c.js

import {c3} from "./commonDeps"