Home > Software engineering >  Error when attempting to import a node module into NuxtJS TypeScript (ES2018)
Error when attempting to import a node module into NuxtJS TypeScript (ES2018)

Time:04-11

I am attempting to import the chess.js module like so:

import Chess from 'chess.js';

This gives me the following error when loading the app locally:

require() of ES Module .../app/node_modules/chess.js/chess.js from .../app/node_modules/vue-server-renderer/build.dev.js not supported. Instead change the require of chess.js in .../app/node_modules/vue-server-renderer/build.dev.js to a dynamic import() which is available in all CommonJS modules.

Well I'm already using an import statement, not require. I've tried playing around with different ways to import the module but nothing is working. I understand this is caused by using TypeScript when creating the NuxtJS app. I'm currently trying to import the chess.js module into a .js file, not a .ts file, and something is getting mistranslated here.

Any ideas?

This is my tsconfig:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@nuxt/types",
      "@nuxtjs/axios",
      "@types/node"
    ]
  },
  "exclude": [
    "node_modules",
    ".nuxt",
    "dist"
  ]
}

UPDATE Converting the .js file to .ts and running 'npm i --save-dev @types/chess.js' did the trick. But I'm still wondering if there's a way to get the original JS script to work.

CodePudding user response:

You can try using the import() function with JavaScript.

You need to follow these steps to accomplish it.

  1. Remove the following line from package.json.

    {
      "type": "module"
    }
    
  2. Change your import statement to the below. Make sure you are using the LTS version of Node.js, as older versions don't support top-level await!

    const chess = await import("chess.js");
    

This should remove the error, while also allowing you to use JavaScript.

  • Related