developit / microbundle

📦 Zero-configuration bundler for tiny modules.
https://npm.im/microbundle
MIT License
8.03k stars 362 forks source link

[Question] Build for both client side and server side #980

Closed multivoltage closed 2 years ago

multivoltage commented 2 years ago

I built a library which is a wrapper of some api. So my lib uses axios (included in bundle). I want to delivery something that work for example:

In the second case call to lambda from a page throw: XMLHttpRequest is not defined. There is a possibility to do that? Thanks

rschristian commented 2 years ago

You'll need to create separate builds for each environment using --target.

Microbundle targets web by default, but you can use --target node to output Node-compatible bundles.

https://github.com/developit/microbundle#all-cli-options-

multivoltage commented 2 years ago

Yes I know but using target = node produce same file with same extension. So is impossible to have both js for both environment. Maybe I forgot somethings?

rschristian commented 2 years ago

using target = node produce same file with same extension

If you're just referring to the naming collision, there's plenty of options there, from renaming to nesting.

{
  // package.json
  "scripts": {
    "build:web": "microbundle -o dist/web",
    "build:node": "microbundle -o dist/node --target node"
  }
}
multivoltage commented 2 years ago

Thanks @rschristian . So how describe package json in this case?

  "exports": {
    "require": "./dist/node/a.cjs",
    "default": "./dist/node/a-modern.js"
  },
  "main": "./dist/node/a.cjs",
  "module": "./dist/node/a.module.js",

Sorry but I cannot undestand where put /web :)

rschristian commented 2 years ago

Depends a bit on what tools you want to support. Generally, "module" or "browser" work pretty well:

{
  "exports": {
    "module": "./dist/web/...",
    ...
  }
}

You might want to browse Webpack's package exports docs. It contains info for a bunch of different tools, not just Webpack.