Skip to content

Add support to ES Modules #2981

Closed
Closed

Description

@Rigo-m

What are you trying to achieve?

Use Sharp in a nuxt nitro environment

What would you expect the API to look like?

Sharp should export an .mjs file so that it can be used in environments that doesn't support .cjs

What alternatives have you considered?

None but any suggestion is welcomed

Activity

  1. lovell commented on Nov 17, 2021

    @lovell
    Owner
  2. Rigo-m commented on Nov 18, 2021

    @Rigo-m
    Author

    It should work, I think. Otherwise, you can use https://github.com/unjs/mlly to port sharp into ESM 😛

    @pi0 any suggestions?

  3. pi0 commented on Nov 18, 2021

    @pi0
    Contributor

    @Rigo-m Sharp can be imported inside Node.js ESM files and also working fine with Nuxt Nitro (the only limitation is you cannot deploy to Workers because of Node.js bindings). BTW you might like to use ipx which is based on Sharp but easier to integrate. Check this example: https://codesandbox.io/s/quirky-currying-3259v?file=/server/api/ipx.ts

    @lovell While Node.js ESM can work with CJS libraries and bundlers like webpack/rollup allow mixed syntax (that's how nitro workers) it would be nice if Sharp also adds exports field. This can make support less hacky and more ESM native. If you want me can make a PR to improve packages' ESM support. Some of popular packages even considered being esm-only.

  4. lovell commented on Nov 18, 2021

    @lovell
    Owner

    Thanks for confirming, a PR to add a thin ESM wrapper and suitable exports to allow dual-usage would be most welcome. If it's possible to add a unit test for the wrapper, that would be great too.

    And thank you Pooya for all your work on Nuxt and the Vue ecosystem!

  5. pi0 commented on Apr 19, 2022

    @pi0
    Contributor

    Hi @lovell. Just pinging to say still would love to contribute to this for ESM support! @danielroe is also an ESM expert who might help on this as well :)

  6. robinscholz commented on May 16, 2022

    @robinscholz

    @pi0 Do you happen to have an example with sharp and nuxt nitro somewhere? Running into problems, where sharp is a dependency of a package that is imported for a server side api in nuxt 3.

  7. pi0 commented on May 16, 2022

    @pi0
    Contributor

    Usage is in sandbox comment above but official Nuxt3 integration is coming soon with Image module.

  8. shtse8 commented on Jul 13, 2022

    @shtse8

    looking forward to this support

  9. spartanz51 commented on Nov 23, 2022

    @spartanz51
    import { createCommonJS } from 'mlly'
    const { __dirname, __filename, require } = createCommonJS(import.meta.url)
    import sharp from 'sharp'
    
  10. TimisRobert commented on Dec 3, 2022

    @TimisRobert
    import { createCommonJS } from 'mlly'
    const { __dirname, __filename, require } = createCommonJS(import.meta.url)
    import sharp from 'sharp'
    

    I'm trying to make it work with esbuild, but I always get __dirname is not defined :(

  11. vikyw89 commented on May 11, 2023

    @vikyw89
  12. maddsua commented on Aug 1, 2023

    @maddsua
  13. florian-lefebvre commented on Mar 17, 2026

    @florian-lefebvre
    Contributor

    @lovell I started looking into this. I think an important question to answer to start would be: should sharp ship as ESM-only? AFAIK pros and cons are:

    Pros Cons
    ESM+CJS Compatibility, no change needed to engines.node Increase in size. Needs duplicated files or a build system (eg. tsdown)
    ESM-only Easy, just convert Compatibility, needs engines.node as ^20.19.0 || >=22.12.0 to support require(esm) without a flag
  14. guillaumekh commented on Mar 17, 2026

    @guillaumekh

    needs engines.node as ^20.19.0 || >=22.12.0 to support require(esm) without a flag

    IMHO it would be a fair ask.

    Here are some interesting stats on the current CJS/ESM landscape if anyone is curious.

  15. florian-lefebvre commented on Mar 17, 2026

    @florian-lefebvre
    Contributor

    Apparently if Sharp was ESM-only, this dynamic import

    const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`);
    would not work if Sharp was imported by a CJS file.

    So basically that leaves 2 solutions:

    • ESM+CJS, no change in behavior
    • ESM-only with an API change eg. sharp = await loadSharp()
  16. Bessonov commented on Mar 17, 2026

    @Bessonov

    @florian-lefebvre In my opinion, it’s a good idea to switch to ESM-only and, for legacy apps, maybe create a repository for a community-driven CommonJS-only fork.

    @guillaumekh We’ve been running sharp in Lambda since 2016. The last update was in 2018, I think, and it’s still working. I am still happy with webpack for bundling and reducing size.

  17. lovell commented on Mar 17, 2026

    @lovell
    Owner

    For those interested in ESM as an aid for code bundling, some of the dynamic requires have been replaced with static paths via commit fff7431, which will be part of the next release and is independent of any changes being discussed here.

    In terms of supporting both ESM+CJS (until Node.js 22 reaches end of life), does anyone know if "approach 1" documented at https://github.com/nodejs/package-examples/tree/main/guide/07-dual-packages#approach-1-use-an-es-module-wrapper will work?

  18. dereekb commented on Mar 18, 2026

    @dereekb

    It should work if the current build is going to continue to build to CommonJS. The magic around the importing is mostly just in the package.json that explains how certain environments should import the module between the "types" and "exports".

    If you use "module" as the type in project.json (like the article suggets) just remember to name the CommonJS export .cjs instead of .js, since in an ESM environment .js files would be treated as ESM by default.

    You could try this and retain the current .js files output:

    wrapper.mjs

    import sharp from './index.js';
    export default sharp;

    package.json changes

    {
        "type": "commonjs",
        "main": "./lib/index.js",
        "types": "./lib/index.d.ts",
        "exports": {
          "types": "./lib/index.d.ts",
          "import": "./lib/wrapper.mjs",
          "require": "./lib/index.js"
        }
      }
    

    If you're going to build to ESM first though then you might need something different as ESM environments seems to be able to deal with the internal require(...) calls, but CommonJS environments won't handle import statements.

  19. florian-lefebvre commented on Mar 18, 2026

    @florian-lefebvre
    Contributor

    AFAIK using an ES module wrapper is called Faux-ESM, which has no real benefit over just CJS

  20. Yug-Damon commented on Mar 29, 2026

    @Yug-Damon

    Keywords: Sharp + Electron + ESM bundling

    For anyone trying to bundle Sharp in an Electron app while keeping an ESM build, here’s what I learned after spending quite some time debugging this.

    I initially explored approaches like this one:
    github:image-optimizer-electron
    It works, but feels more like a workaround than a solid solution.

    Key observations

    1. Sharp is CommonJS → It cannot be properly bundled into an ESM build and must be marked as external.
    2. Native dependencies live in @img/* → These contain platform-specific binaries and must be unpacked from the asar.
    3. Runtime resolution constraint → sharp expects its dependencies (@img/*, detect-libc, semver, etc.) to be located relative to itself inside node_modules.
    4. asar implication → Because of this resolution logic, both sharp and its native deps must live in app.asar.unpacked, otherwise runtime resolution fails.

    Practical solution

    • Keep sharp and its native dependencies in app.asar.unpacked
    • Redirect imports at build time instead of trying to bundle

    Example using an esbuild plugin:

    const SharpElectronBundlerPlugin = {
      name: 'SharpElectronBundler',
      setup(build) {
        build.onResolve({ filter: /^sharp$/ }, (args) => {
          if (isProd) {
            return {
              external: true,
              path: '../../app.asar.unpacked/node_modules/sharp/lib/index.js'
            }
          }
          return { path: args.path }
        })
      },
    }

    And in your Electron config:

    {
      "build": {
        "asarUnpack": [
          "node_modules/sharp/**/*",
          "node_modules/@img/**/*",
          "node_modules/detect-libc/**/*",
          "node_modules/semver/**/*"
        ]
      }
    }

    Conclusion
    Even with ESM tooling (esbuild, Vite, etc.), Sharp behaves as a runtime-resolved native module, not a bundle-friendly dependency.

    So the reliable approach today is:

    • Do not bundle it
    • Unpack it
    • Redirect imports

    If someone turns this into a reusable plugin/package, that would definitely help the ecosystem 👍

    To address more fundamentally the issue I would suggest :

    import {sharpBinariePath} from "sharp-static"
    import sharp from "sharp"
    sharp.setBinaryPath(sharpBinariePath)
  21. added this to the v0.35.0 milestone on Apr 17, 2026
  22. lovell commented on Jun 10, 2026

    @lovell
    Owner

    sharp v0.35.0 now available with dual ESM/CJS support. Merci beaucoup to @florian-lefebvre for helping with this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions