最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - return old(m, filename); Error [ERR_REQUIRE_ESM]: require() of ES Module - Stack Overflow

programmeradmin3浏览0评论

i'm trying to do an integration with the unsplash api but i'm getting,

when I try to run the script by ts-node like:

ts-node unsplash.ts

there is error for:

C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\USER\Desktop\tindin\node_modules\node-fetch\src\index.js from C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts not supported.
Instead change the require of index.js in C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.require.extensions.<computed> [as .js] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729:20)
    at Object.<anonymous> (C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts:23:30)
    at Module.m._compile (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:735:29)
    at Object.require.extensions.<computed> [as .ts] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:737:16)
    at main (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:238:16)
    at Object.<anonymous> (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:351:5) {
  code: 'ERR_REQUIRE_ESM'
}

my code

import { createApi } from 'unsplash-js';
import * as nodeFetch from 'node-fetch'

const unsplash = createApi({
  accessKey: 'MY_ACCESS_KEY',
  fetch: nodeFetch.default as unknown as typeof fetch,
});

i'm following the reference of the unsplash documentation itself link :

my package.json

{
  "name": "typescript",
  "version": "1.0.0",
  "main": "server.js",
  "license": "MIT", 
  
  "scripts": {
    "dev": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
    "lint": "eslint . --ext .ts",
    "lint-fix": "eslint . --ext .ts --fix"
  },
  "devDependencies": {
    "@types/node": "^17.0.8",
    "@typescript-eslint/eslint-plugin": "^5.9.0",
    "@typescript-eslint/parser": "^5.9.0",
    "eslint": "^8.6.0",
    "ts-node-dev": "^1.1.8",
    "tsconfig-paths": "^3.12.0",
    "typescript": "^4.5.4"
  },
  "dependencies": {
    "node-fetch": "^3.1.1",
    "unsplash-js": "^7.0.15"
  }
}
  

my tsconfig.json

{
  "compilerOptions": {
   
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    "outDir": "./build",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                         /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "noImplicitAny": true,                    /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": ".",                       /* Base directory to resolve non-absolute module names. */
   
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "resolveJsonModule": true,                /* Include modules imported with '.json' extension */
    "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
  },
  "exclude": [
    "node_modules",
    "build"
  ],
  "include": [
    "src/**/*"
  ]
}

I add "type": "module" in package.json file.

{
  "name": "typescript",
  "version": "1.0.0",
  "type": "module",
...
}

I get this error

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts
    at new NodeError (node:internal/errors:371:5)
    at Object.file: (node:internal/modules/esm/get_format:72:15)
    at defaultGetFormat (node:internal/modules/esm/get_format:85:38)
    at defaultLoad (node:internal/modules/esm/load:13:42)
    at ESMLoader.load (node:internal/modules/esm/loader:303:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:230:58)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:244:11)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

i'm trying to do an integration with the unsplash api but i'm getting,

when I try to run the script by ts-node like:

ts-node unsplash.ts

there is error for:

C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\USER\Desktop\tindin\node_modules\node-fetch\src\index.js from C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts not supported.
Instead change the require of index.js in C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts to a dynamic import() which is available in all CommonJS modules.
    at Object.require.extensions.<computed> [as .js] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:729:20)
    at Object.<anonymous> (C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts:23:30)
    at Module.m._compile (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:735:29)
    at Object.require.extensions.<computed> [as .ts] (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:737:16)
    at main (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:238:16)
    at Object.<anonymous> (C:\Users\USER\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js:351:5) {
  code: 'ERR_REQUIRE_ESM'
}

my code

import { createApi } from 'unsplash-js';
import * as nodeFetch from 'node-fetch'

const unsplash = createApi({
  accessKey: 'MY_ACCESS_KEY',
  fetch: nodeFetch.default as unknown as typeof fetch,
});

i'm following the reference of the unsplash documentation itself link : https://github.com/unsplash/unsplash-js

my package.json

{
  "name": "typescript",
  "version": "1.0.0",
  "main": "server.js",
  "license": "MIT", 
  
  "scripts": {
    "dev": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
    "lint": "eslint . --ext .ts",
    "lint-fix": "eslint . --ext .ts --fix"
  },
  "devDependencies": {
    "@types/node": "^17.0.8",
    "@typescript-eslint/eslint-plugin": "^5.9.0",
    "@typescript-eslint/parser": "^5.9.0",
    "eslint": "^8.6.0",
    "ts-node-dev": "^1.1.8",
    "tsconfig-paths": "^3.12.0",
    "typescript": "^4.5.4"
  },
  "dependencies": {
    "node-fetch": "^3.1.1",
    "unsplash-js": "^7.0.15"
  }
}
  

my tsconfig.json

{
  "compilerOptions": {
   
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    "outDir": "./build",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                         /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "noImplicitAny": true,                    /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": ".",                       /* Base directory to resolve non-absolute module names. */
   
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "resolveJsonModule": true,                /* Include modules imported with '.json' extension */
    "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
  },
  "exclude": [
    "node_modules",
    "build"
  ],
  "include": [
    "src/**/*"
  ]
}

I add "type": "module" in package.json file.

{
  "name": "typescript",
  "version": "1.0.0",
  "type": "module",
...
}

I get this error

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\USER\Desktop\tindin\src\api\services\unsplash.ts
    at new NodeError (node:internal/errors:371:5)
    at Object.file: (node:internal/modules/esm/get_format:72:15)
    at defaultGetFormat (node:internal/modules/esm/get_format:85:38)
    at defaultLoad (node:internal/modules/esm/load:13:42)
    at ESMLoader.load (node:internal/modules/esm/loader:303:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:230:58)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:244:11)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
Share Improve this question asked Jan 21, 2022 at 11:32 Lucas Amorim LimaLucas Amorim Lima 2511 gold badge3 silver badges3 bronze badges 3
  • You can try changing "module": "commonjs" to "module": "esnext" in tsconfig.json. – tromgy Commented Jan 21, 2022 at 11:44
  • 1 @tromgy did not work replace to "module": "esnext", continues with the same error Unknown file extension ".ts" – Lucas Amorim Lima Commented Jan 21, 2022 at 12:36
  • 1 This appears to be a sort of infamous "catch-22" problem with ts-node. You can check this stackoverflow thread. I think your best bet is to simply compile first, and then run the resulting .js file with node. Keep "type": "module" in your package.json and "module": "esnext" in tsconfig.json. – tromgy Commented Jan 21, 2022 at 14:00
Add a comment  | 

2 Answers 2

Reset to default 4

I fixed using this instruction:

https://github.com/TypeStrong/ts-node/issues/1007

Recommend reading about wider context:

https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

Summary:

  1. in tsconfig.json
    "module": "ESNext",                                  /* Specify what module code is generated. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
  1. in package.json
  "type": "module",
  1. change default imports from node build-in modules eg.:
import os from 'os';

to

import {homedir} from 'os';

or

import fs from 'fs';

to

import {existsSync, readFileSync, writeFileSync} from 'fs';
  1. Run with --esm flag
npx ts-node --esm src/index.ts

Similar questions:

  • How to use ts-node ESM with node modules?
  • https://github.com/TypeStrong/ts-node/issues/1007#issuecomment-1163471306
  • chalk - Error [ERR_REQUIRE_ESM]: require() of ES Module

this tsconfig.json file works for me.

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ESNext",
    "esModuleInterop": true
  },
  "ts-node": {
    "esm": true
  }
}

Note: don't forget to make "type":"module" in your package.json file.

my package.json file looks like this.

{
  "name": "nodejs-cli",
  "version": "1.0.0",
  "description": "description",
  "type": "module",
  "scripts": {
    "dev": "nodemon cli.ts"
  },
  "license": "MIT",
  "dependencies": {
    "inquirer": "^9.2.12"
  },
  "devDependencies": {
    "@types/inquirer": "^9.0.7",
    "@types/node": "^20.10.7",
    "nodemon": "^3.0.2",
    "ts-node": "^10.9.2",
    "typescript": "^5.3.3"
  }
}
发布评论

评论列表(0)

  1. 暂无评论