unjs/unimport

Auto extract package exports

pi0 opened this issue · 0 comments

pi0 commented

We can directly use the npm package to automatically detect their exports and use it as a preset. Currently, it is only possible to use manual presets and a list of their exports.

In order to extract exports, we have 3 possible ways:

  • Actually require package in an isolated runtime and check the exports
  • Use static syntax analyses to detect exports
  • Use metadata directly exported from packages

Using the last method is safest because packages can exactly annotate their exports and use a built step plugin (unbuild or rollup) to automate this meta generation process into dist/unimport.json. We can then refer it from package.json using "unimport": "./dist/unimport.json"

When packages are not bundled in this way, we can fallback to mlly.resolveModuleExportNames and use fast static analyzes to extract export names.

In order to have better control over auto-infered exports, we might exprot a filter function from presets. I imagine preset looking like this:

presets: [{
  package: 'h3',
  exports: 'auto' | 'analyze' // Default is auto - Tries `autoImport` in pacakge.json then analyzes
  ignore: ['h', (name) => !name.startsWith('use')]
}]

In order to speed up the performance, we might use global cache in {os.tmpDir}/unimport/{package}/{version}/exports.json containing exports and an integrity field to validate cache entry.

(This is a summary of discussing together with @antfu)