giuseppeg / awesome-ideas

💡😍 Small side project ideas for people to pick up and implement
10 stars 0 forks source link

BUNDLE_ENV: export modern/legacy library bundles based on bundler settings #2

Open giuseppeg opened 4 years ago

giuseppeg commented 4 years ago

Often library authors ship a ESM bundle of their library where only the import/export syntax is preserved and the rest is all transpiled.

The reason for this is that even though bundlers like webpack support ESM and often prefer them over CommonJS (they read the module field in package.json), they are configured to not transpile node_modules using the app preferences (eg. browserlist or Babel preset env settings).

If the app author is supporting an old browser (eg. IE11) and consumes a non transpiled modern bundle the app would break on that browser. For this reason most of the times lib authors transpile their code.

the idea

Library authors can already create entry points that export code conditionally (bundlers know how to deal with this)

// dist/index.js
import dev from './myLib.dev.js'
import prod from './myLib.prod.js'

export default process.env.NODE_ENV === 'production' ? prod : dev

If bundlers would automatically set a BUNDLE_ENV variable, libraries authors could use it to export modern or legacy bundles accordingly:

// dist/index.js
import modern from './myLib.modern.js'
import legacy from './myLib.legacy.js'

export default process.env.BUNDLE_ENV === 'modern' ? modern : legacy

In webpack this would be another option like mode.

giuseppeg commented 4 years ago

Jason Miller suggested that Export Maps might be a better solution to this problem, or simply globals without process.env. which is obviously not available in the browser.

The problem we both see is how are we going to determine whether the ENV is modern enough? Quoting Jason:

would it be enough to target type=module features as "modern"