If possible, the requires should be listed manually
let DynamicThings = {
Foo: require('./foo.js'),
Bar: require('./bar.js'),
};
Otherwise, create a template for npm pre-publish (which also runs on npm install, locally) or similar:
let js = `"use strict";
let DynamicThings = {};
`;
Fs.readdir(`./things/`).forEach(function (node) {
// the final require will have the literal value of ${node}, not the variable
js += `DynamicThings.${node} = require(\`./things/${node}\`);\n`
});
js += `\n`;
Fs.writeFile(`./generated-things.js`, js, `utf8`);
Require the generated file:
let DynamicThings = require('/generated-things.js');
Rationale
tsc
) can't read exports that require runtime code to examineExample: Exports
Bad
Good
Example: Dynamic Imports
Bad
Good
If possible, the requires should be listed manually
Otherwise, create a template for
npm pre-publish
(which also runs onnpm install
, locally) or similar:Require the generated file: