Home > Back-end >  Error: Failed to resolve module specifier "highlight.js" in ES6 module compiled from TS
Error: Failed to resolve module specifier "highlight.js" in ES6 module compiled from TS

Time:02-06

I am trying to use the library highlight.js for code highlighting, and it does come with support for ES modules. When I try to use it in a ES6 module compiled from TS, it comes back with the error: Uncaught TypeError: Failed to resolve module specifier "highlight.js". Relative references must start with either "/", "./", or "../". I have installed @types/highlight.js, and highlight.js itself through NPM.

highlight.ts

import hljs from "highlight.js";

hljs.highlightAll();

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2022",
        "module": "CommonJS",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true,
        "outDir": "js",
        "rootDir": "ts",
        "moduleResolution": "node",
        "baseUrl": ".",
        "paths": {
            "highlight.js": ["/node_modules/@types/highlight.js"]
        }
    }
}

I have tried using an importmap as follows, but was faced with a different error: Uncaught SyntaxError: The requested module '../lib/core.js' does not provide an export named 'default'

<script type="importmap">
   { 
      "imports": {
        "highlight.js": "/node_modules/highlight.js/es/core.js"
      } 
   }
</script>

I have also tried changing the module in the tsconfig.json to CommonJS, and I was faced with another error: Uncaught ReferenceError: export is not defined, which was fixed by adding <script>var exports = {};</script> to the DOM. After that, it gave another error: Uncaught ReferenceError: require is not defined, even though I am not using require anywhere.

I am hoping to find a solution that does not use things like Webpack.

CodePudding user response:

Likely need to add "allowJs" in your tsconfig.json

https://www.typescriptlang.org/tsconfig#allowJs

CodePudding user response:

Simple but hacky solution. I used a script tag to get highlight.min.js, and just @ts-ignore any code in the highlight.ts.

  • Related