truffle
truffle copied to clipboard
Support ESM
Issue
Truffle doesn't support ESM.
Steps to Reproduce
- Set
"type": "module"
inpackage.json
. - 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
We will look into this issue. Thanks for raising this!
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.
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
Just found a (seemingly undocumented) --config
CLI argument that helped with that.
@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 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.
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).