Hey.. I have a question about `exports` ... I hav...
# typescript
a
Hey.. I have a question about
exports
... I have a pulumi app that is modularized in a simple Typescript fashion. I have a "MyModules" folder and I have files in there with exported functions. This all works great from running pulumi and letting me have manageable files to deal with. What doesn't work though is if one of these functions needs to export something out to the pulumi service as a stack output.
export const keyvaultId = keyvault.id
does not work in the function in the module.
export
has to be outside of the function.
exports["keyvaultId"] = keyvault.id
and
exports.keyvaultId = keyvault.id
which work in the function do not seem to be getting exported into the stack outputs. If I put an
exports.<name> = value;
in the top-level index.ts, it does work. I would have expected the exports to work anywhere I use it and the stack output is correctly updated. Is this an incorrect expectation?
l
The pulumi app is in most ways a normal TypeScript module. Exports from the module (index.ts) are its exports. All other files are their own modules, which the Pulumi app can use. But the exports of those other files are their exports, not index.ts' exports. The first few paragraphs on this page explains it well: https://www.typescriptlang.org/docs/handbook/modules.html
Exports have rules from TypeScript, including that they must be at the top level, not inside classes or functions.
s
I ran into this as well and now just pass anything to export back to index.ts for actual export
👍 1
l
You can export things from one module without importing them / passing them back. The syntax is under "Re-exports" on the link above.
a
@little-cartoon-10569 I understand exports. I didn't think that aggregating exports is called re-exports, but I do that as well. But pulumi (maybe typescript) has a feature where you can dynamically add properties (with values), in a function, to the
exports
object and they get exported when you are in the main pulumi index.ts. I couldn't get that approach to work in the modules, which are basically only an exported function. So now, my module functions all return a
{}:any
and they are all collected and then added to the
exports
object in the top-level index.ts.
Copy code
var toOutputs : any = {};

var newOutputs = module.Function();
toOutputs = {...toOutputs, ...newOutputs}
<repeat as needed>

Object.keys(toOutputs).forEach( key => { exports[key] = toOutputs[key]});
l
Ah yes. Sorry, haven't used that notation. It seems to be normal CommonJS/TS though? I see it on that same page I linked earlier, under "Code Generation for Modules" / CommonJS. The Stacks page in the Pulumi docs uses that notation and says that only top level exports become stack outputs: https://www.pulumi.com/docs/intro/concepts/stack/#outputs
a
I wonder if I could pass the
exports
object into my module functions. 😄