Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clouedoc/16e2d2cbf7b3058648fc704ee7aec18e to your computer and use it in GitHub Desktop.
Save clouedoc/16e2d2cbf7b3058648fc704ee7aec18e to your computer and use it in GitHub Desktop.
SWC converts dynamic `import` calls to `require`, and it made me crazy. But I found the solution!

SWC converts dynamic import calls to require

This document describes the problem I faced as well as the solution

Problem

I need to access an ESM module from my output CJS project.

(I don't understand all of these terms well)

To do so, I need to use import. It's the only way that'll work.

A regular import execa from 'execa' doesn't work because Ocliff doesn't like this. It only likes import.

So, I decided to use import, but something weird happened...

➜  git:(prod) ✗ ns dev:apk:patch ./apk/aptoide/
    Error: require() of ES Module 
    /root/project/node_modules/execa/index.js from 
    /root/project/lib/commands/dev/apk/patch.js not 
    supported.
    Instead change the require of index.js in 
    /root/project/lib/commands/dev/apk/patch.js to a 
    dynamic import() which is available in all CommonJS modules.
    Code: ERR_REQUIRE_ESM

Indeed, SWC was converting my import to require!!!

Solution

I found the option that asks SWC to not touch my dynamic imports.

It's called ignoreDynamic.

Here is my .swcrc for reference:

{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "dynamicImport": true
    },
    "target": "es2022"
  },
  "module": {
    "type": "commonjs",
    "ignoreDynamic": true
  }
}

Good luck on your journey!

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