Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module #535

Closed
MichaelGradek opened this issue Mar 11, 2022 · 33 comments
Closed

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module #535

MichaelGradek opened this issue Mar 11, 2022 · 33 comments
Assignees
Labels

Comments

@MichaelGradek
Copy link

I just installed the library onto my TypeScript project and I get the following error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/mike/project/node_modules/file-type/index.js
require() of ES modules is not supported.

Any idea why this may be happening?

"file-type": "^17.1.1"

@sindresorhus
Copy link
Owner

Duplicate of #525

@sindresorhus sindresorhus marked this as a duplicate of #525 Mar 12, 2022
@Borewit Borewit self-assigned this Mar 12, 2022
@Borewit
Copy link
Collaborator

Borewit commented Mar 12, 2022

To import a ES module from a CommonJs module wiritten in TypeScript, is very tricky.
The import is transpiled to require, that is why you get the error require() of ES modules is not supported.

Have look to this artice How to Correctly Use TypeScript Module Import Syntax and Settings in Various Circumstances, check When a CommonJS module imports an ES Module. (I have to say, I did followed this guidance myself yet).

Or use a quick and dirty workaround:

/**
 * Import 'file-type' ES-Module in CommonJS Node.js module
 */
(async () => {
  const { fileTypeFromFile } = await (eval('import("file-type")') as Promise<typeof import('file-type')>);

  const type = await fileTypeFromFile('fixture.skp');
  console.log(type);
})();

The quick and dirty workaround example can be found in the PR: Borewit/file-type-example#1

If you got a cleaner solution, I like to get your feedback @MichaelGradek.

@Borewit Borewit reopened this Mar 12, 2022
@Luxcium
Copy link

Luxcium commented Mar 15, 2022

I didnt read the error message at first so I tried const fileTypeFromFile = require('file-type'); instead of import { fileTypeFromFile } from 'file-type';

then realized neither are working

❯ ts-node "${PROJECT}/src/utilities/sharp-phash/__sharp-phash-working.ts"
${PROJECT}/src/packages/file-path/getPathWithStats.ts:4
import { FileTypes } from './tools';
                    ^
Error [ERR_REQUIRE_ESM]: require() of ES Module ${PROJECT}/node_modules/file-type/index.js from ${PROJECT}/src/packages/file-path/getPathWithStats.ts not supported.
Instead change the require of index.js in ${PROJECT}/src/packages/file-path/getPathWithStats.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (${PROJECT}/src/packages/file-path/getPathWithStats.ts:4:21)
    at Module.m._compile (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:786:29)
    at Object.require.extensions.<computed> [as .ts] (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:788:16)
    at Object.<anonymous> (${PROJECT}/src/packages/file-path/utils/index.ts:4:26)
    at Module.m._compile (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:786:29)
    at Object.require.extensions.<computed> [as .ts] (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:788:16)
    at Object.<anonymous> (${PROJECT}/src/packages/file-path/tools/dirListWithFileType/currentPath.ts:4:17)
    at Module.m._compile (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:786:29)
    at Object.require.extensions.<computed> [as .ts] (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:788:16)
    at Object.<anonymous> (${PROJECT}/src/packages/file-path/tools/dirListWithFileType/index.ts:4:21)
    at Module.m._compile (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:786:29)
    at Object.require.extensions.<computed> [as .ts] (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:788:16)
    at Object.<anonymous> (${PROJECT}/src/utilities/sharp-phash/__sharp-phash-working.ts:7:31)
    at Module.m._compile (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:786:29)
    at Object.require.extensions.<computed> [as .ts] (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/index.js:788:16)
    at main (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/bin.js:292:16)
    at Object.<anonymous> (${HOME}/.nvm/versions/node/v17.5.0/lib/node_modules/ts-node/dist/bin.js:405:5) {
  code: 'ERR_REQUIRE_ESM'
}

@Luxcium
Copy link

Luxcium commented Mar 15, 2022

and when using the compiled version of the code:

❯ node "/home/luxcium/projects/parallel-mapping/out/src/utilities/sharp-phash/__sharp-phash-working.js"
/home/luxcium/projects/parallel-mapping/out/src/packages/file-path/getPathWithStats.js:4
const file_type_1 = require("file-type");
                    ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/luxcium/projects/parallel-mapping/node_modules/file-type/index.js from /home/luxcium/projects/parallel-mapping/out/src/packages/file-path/getPathWithStats.js not supported.
Instead change the require of index.js in /home/luxcium/projects/parallel-mapping/out/src/packages/file-path/getPathWithStats.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/home/luxcium/projects/parallel-mapping/out/src/packages/file-path/getPathWithStats.js:4:21)
    at Object.<anonymous> (/home/luxcium/projects/parallel-mapping/out/src/packages/file-path/utils/index.js:4:26)
    at Object.<anonymous> (/home/luxcium/projects/parallel-mapping/out/src/packages/file-path/tools/dirListWithFileType/currentPath.js:4:17)
    at Object.<anonymous> (/home/luxcium/projects/parallel-mapping/out/src/packages/file-path/tools/dirListWithFileType/index.js:4:21)
    at Object.<anonymous> (/home/luxcium/projects/parallel-mapping/out/src/utilities/sharp-phash/__sharp-phash-working.js:7:31) {
  code: 'ERR_REQUIRE_ESM'
}

Node.js v17.7.1


my package.json and tsconfig.json are available at the link: github.com/[...]/package.json

@Luxcium
Copy link

Luxcium commented Mar 16, 2022

I can not do any of the different methods I am aware of:

getPathWithStats.ts:
Screenshot_000001_20220315_200858

Still getting:

Error [ERR_REQUIRE_ESM]: require() of ES Module ${PROJECT}/node_modules/file-type/index.js from ${PROJECT}/src/packages/file-path/getPathWithStats.ts not supported.
Instead change the require of index.js in ${PROJECT}/src/packages/file-path/getPathWithStats.ts to a dynamic import() which is available in all CommonJS modules.
    at ${PROJECT}/src/packages/file-path/getPathWithStats.ts:39:86
    at async ${PROJECT}/src/packages/file-path/getPathWithStats.ts:39:38 {
  code: 'ERR_REQUIRE_ESM'
}

@azhengyongqin
Copy link

Stupid updates

@kkan0615
Copy link

It makes me super annoying!!!!!!

@airone01
Copy link

Thanks @Borewit, I'm using your workaround for now, but somehow I keep getting syntax errors from await not being on top, even tough it is, so I have to wrap everything in an async function.
Pain.

@Thomas-1985
Copy link

I really want to use your npm in my TypeScript project and tried import and require, none of them seem to work. The error message is
`
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /my-project/index.js
require() of ES modules is not supported.
require() of /my-project/node_modules/file-type/index.js from /my-project/users.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /my-project/node_modules/file-type/package.json.

at new NodeError (internal/errors.js:322:7)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (/my-project/users.ts:44:1)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/my-project/node_modules/ts-node/src/index.ts:1459:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10) {

code: 'ERR_REQUIRE_ESM'
}
[nodemon] app crashed - waiting for file changes before starting...
`

Please make it so i can use the npm like with every other by using either import or require

@dedeard
Copy link

dedeard commented Apr 1, 2022

hahahha, i like this update.

@dedeard
Copy link

dedeard commented Apr 1, 2022

this makes me happy
npm i [email protected]

bmaupin added a commit to bmaupin/resx-extractor that referenced this issue Apr 6, 2022
So that we can avoid the dynamic import workaround monstrosity (sindresorhus/file-type#535)
@netojose
Copy link

I had to make the same thing @dedeardiansya told, downgrade.
I'm watching changes on this issue, when be solved, I update the package.

@emimarz
Copy link

emimarz commented May 18, 2022

@netojose to which version do you downgrade?

@jloehel
Copy link

jloehel commented May 18, 2022

@netojose to which version do you downgrade?

The 17.0.0 is breaking everything. The versions before should work:

...
    "file-type": "^16.5.3",
...

@emimarz
Copy link

emimarz commented May 18, 2022

thanks

@netojose
Copy link

@emimarz , the version @jloehel said: "^16.5.3"

@RemyMachado
Copy link

Note that the function fileTypeFromFile is named fromFile with the version 16.5.3

const { fromFile } = require('file-type')

@sindresorhus
Copy link
Owner

@prernagp
Copy link

prernagp commented Jun 6, 2022

This is still not working... have tried multiple things in my loopback project. I really need the latest fix but unable to do so. @sindresorhus @Borewit pls help

@T-vK
Copy link

T-vK commented Jul 12, 2022

Are there any plans to make file-type CommonJS-compatible again?

Are there any maintained alternatives out there that support getting the mime-type from a buffer like FileType.fromBuffer?

@vaibhavkumar-sf
Copy link

Same issue in LoopBack Project

@prernagp
Copy link

prernagp commented Jul 15, 2022

@T-vK @vaibhavkumar-sf We have managed to use it like this:-

`const {fileTypeFromBuffer} = await (eval('import("file-type")') as Promise<typeof import('file-type')>);

const fileTrueType = await fileTypeFromBuffer(request);`

Using @Borewit example code:- https://github.com/Borewit/file-type-example/pull/1/files

@T-vK
Copy link

T-vK commented Jul 15, 2022

@prernagp Thank you, I had to modify it a bit, but it basically works.

const exampleGifBuffer = Buffer.from("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", "base64");

async function main() {
    const { fileTypeFromBuffer } = await import("file-type");
    const type = await fileTypeFromBuffer(exampleGifBuffer);
    console.log(type);
}

main().catch(console.error);
$ node index.js 
{ ext: 'gif', mime: 'image/gif' }

The only issue is that I can't use await at the top-level...

Edit:
Well, since fileTypeFromBuffer is async anyway, I might as well do it like this:

const exampleGifBuffer = Buffer.from("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", "base64");
const fileTypeFromBuffer = async buf =>  {
    fileTypeFromBuffer._cached = fileTypeFromBuffer._cached || (await import("file-type")).fileTypeFromBuffer
    return fileTypeFromBuffer._cached(buf)
}

async function main() {
    const type = await fileTypeFromBuffer(exampleGifBuffer);
    console.log(type);
}

main().catch(console.error);

It makes sure the import is only called once.

@Borewit Borewit closed this as completed Jul 29, 2022
@vtereshyn
Copy link

@netojose to which version do you downgrade?

The 17.0.0 is breaking everything. The versions before should work:

...
    "file-type": "^16.5.3",
...

this version has an audit issue.

@netojose
Copy link

netojose commented Sep 8, 2022

@vtereshyn , thanks for share this security information. So, we need to choose between the both options (make necessary changes to project to became full ESM, or accept the security issue :( )

@vtereshyn
Copy link

@vtereshyn , thanks for share this security information. So, we need to choose between the both options (make necessary changes to project to became full ESM, or accept the security issue :( )

Yes. But I have huge project written in Typescript and I don't have an ability to change everything just now. That's why I am working on fork of this repo so I can use commonjs

@Borewit
Copy link
Collaborator

Borewit commented Sep 9, 2022

or accept the security issue :( )

No need for that, that has been addressed in version v16.5.4 @netojose.

@cheng-alvin
Copy link

cheng-alvin commented Jan 4, 2023

"file-type": "^16.5.3",

That's it! Thanks!
Just a side note if you are importing 'fileTypeFromBuffer' (For determining type in v1.18) just modify it to 'fromBuffer'.
Otherwise, it will not compile as it is not featured in 'v1.16.x'

@nkemcels
Copy link

Downgrade to version 16
yarn add file-type@16

@berenar
Copy link

berenar commented Aug 30, 2023

My two cents here, upgrading to yarn 3 worked for me!

@soydev019
Copy link

I have the same issue, had to downgrade to v16.5.4 to make it work

@Shandur
Copy link

Shandur commented Jul 23, 2024

Thanks to @Borewit - it helped 🙌

@max-degterev
Copy link

max-degterev commented Sep 2, 2024

Did anyone fork this package with prober build step already?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests