I'm currently experimenting with the highlight.js library for code highlighting, and while it does support ES modules, I encountered an issue when trying to use it in an ES6 module compiled from TypeScript. The error message that pops up is:
Uncaught TypeError: Failed to resolve module specifier "highlight.js". Relative references must start with either "/", "./", or "../".
Despite having installed @types/highlight.js and highlight.js itself via 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"]
}
}
}
In my attempt to resolve this issue, I tried implementing an importmap as shown below, only to be met with a new 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 also experimented by changing the module
setting in tsconfig.json
to CommonJS
, which led to yet another error:
Uncaught ReferenceError: export is not defined
. This was eventually resolved by adding <script>var exports = {};</script>
to the DOM. However, a subsequent error surfaced: Uncaught ReferenceError: require is not defined
, despite not utilizing require anywhere in my code.
I am seeking a resolution that avoids using tools like Webpack.