Skip to content

Instantly share code, notes, and snippets.

@passbyval
Created May 18, 2023 19:35
Show Gist options
  • Save passbyval/b85f79381816c197c5c651b7c0b00d5e to your computer and use it in GitHub Desktop.
Save passbyval/b85f79381816c197c5c651b7c0b00d5e to your computer and use it in GitHub Desktop.
NX Plugin Workaround: Import ESM from CommonJS
/**
* Workaround for NX's lack of ESM support
*
* See the following issues:
* - {@link https://github.com/nrwl/nx/issues/16776 require() of ES Module executor.js ... not supported with custom plugin using es2015 module #16776 }
* - {@link https://github.com/nrwl/nx/issues/15682 ESM Support for Nx Plugins #15682}
*
* @type {<T, P = PromiseLike<T>>(module: string) => P}
*/
const requireEsm = async module => {
return import(module)
}
module.exports = {
requireEsm,
}
@passbyval
Copy link
Author

passbyval commented May 18, 2023

The downside is that you lose automatic type resolution for the imported module, so you'll have to explicitly define it:

import { requireEsm } from './requireEsm'

type IMarkdownTableModule = typeof import('markdown-table')

export const exmapleFunction = async () => {
  const { markdownTable } = await requireEsm<IMarkdownTableModule>('markdown-table')
}

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