truffle icon indicating copy to clipboard operation
truffle copied to clipboard

Support ESM

Open soulofmischief opened this issue 3 years ago • 7 comments

Issue

Truffle doesn't support ESM.

Steps to Reproduce

  1. Set "type": "module" in package.json.
  2. Run truffle.

Expected Behavior

The config loads, and ESM imports are correctly handled.

Actual Results

The configuration doesn't load, because the original-require package which ingests truffle-config.js uses require and not import. The error suggests to change the extension to .cjs, but this just causes a cascade of needing to change extensions until the entire project is .cjs files and no longer a module.

It's impossible to use latest versions of popular tools such as node-fetch which have switched over to ESM, and it's causing dependency rot.

Environment

  • Operating System: Linux (Fedora)
  • Ethereum client: N/A
  • Truffle version: 5.4.12
  • node version: 16.5.0
  • npm version: 7.19.1

soulofmischief avatar Sep 25 '21 18:09 soulofmischief

We will look into this issue. Thanks for raising this!

dongmingh avatar Sep 29 '21 18:09 dongmingh

Thank you!

For anyone snooping for an intermediate fix for ESM packages like node-fetch:

esm.js

const
  fetchPromise = import( 'node-fetch' ).then( mod => mod.default ),
  fetch = ( ...args ) => fetchPromise.then( fetch => fetch( ...args ))


module.exports = { fetch }

This is because dynamic import() is still supported by CommonJS.

soulofmischief avatar Sep 30 '21 08:09 soulofmischief

Any temporary workarounds for this? Changing the truffle-config file extension to .cjs and invoking commands returns the following:

Could not find suitable configuration file.
Truffle v5.5.3 (core: 5.5.3)
Node v17.6.0

Fardinak avatar Mar 08 '22 16:03 Fardinak

Just found a (seemingly undocumented) --config CLI argument that helped with that.

Fardinak avatar Mar 08 '22 16:03 Fardinak

@Fardinak so Truffle looks explicitly for truffle-config.js, if you rename it it will not find it. But you found the workaround; namely to pass the --config flag to the file.

eggplantzzz avatar Mar 08 '22 22:03 eggplantzzz

@eggplantzzz Yes, but unfortunately that did not prove useful in my case after all; since I'm also using Ganach. I gave up when I couldn't add my project.

In the end, I had to move the Truffle directory structure into a subdirectory and add a package.json with type: "commonjs" to work around the issue.

Fardinak avatar Mar 11 '22 11:03 Fardinak

I ran into this while implementing TypeScript support for migrations.

There are likely numerous things that need to be done to support this, and I think the NodeJS docs on the differences between ES modules and CommonJS are a good starting place to identify what needs to be done.

Proper ESM support will likely require several changes to @truffle/require (among other modules).

benjamincburns avatar Jul 19 '22 04:07 benjamincburns