Search code examples
javascriptbundleresbuild

How create bundle with esbuild with import modules


i have this module

import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'
function cidEncoder (obj) {

}
....

when i build module with this command line

"bundle": "./node_modules/.bin/esbuild  ./dist/index.mjs  --bundle   --outfile=./dist/out.mjs",

I have bundle without export default

when i build module with this command line

"build": "./node_modules/.bin/esbuild  ./src/index.js  --target=es2020   --outfile=./dist/index.mjs",

This import not include in module

import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

How can i create module with include all modules in one file ?


Solution

  • It looks like you haven't specified a platform, so the default will be browser, and according to the esbuild docs the output format (which you also haven't specified) will default to iife:

    When the platform is set to browser (the default value):

    • When bundling is enabled the default output format is set to iife, which wraps the generated JavaScript code in an immediately-invoked function expression to prevent variables from leaking into the global scope.

    So given that you're trying to generate an ESM module (i.e. based on the *.mjs extension on the build output file) you'll need an esm output format, which is the default when specifying a neutral platform:

    "bundle": "esbuild  ./src/index.js  --bundle --platform=neutral  --outfile=./dist/out.mjs",
    

    You'll also need to add a default export to your index.js file:

    import * as cborg from 'cborg'
    import { CID } from 'multiformats/cid'
    
    export default function cidEncoder (obj) {
      ...
    }
    

    Hope that helps.