mosaic-code-viewer’s prismjs package not defined

  Kiến thức lập trình

I am using vite wtih rollup to build my Reactjs app.
One of the packages I use is @stoplight/elements-dev-portal. This package depends on @stoplight/mosaic-code-viewer

I had a problem with this package because internally, it uses prismjs with require. So I used vite’s commonjsOptions config to transform this to esm.

commonjsOptions: {
            transformMixedEsModules: true,
            extensions: ['.js', '.cjs'],
        }

This is my current config file:

import { defineConfig, } from 'vite';
import react from '@vitejs/plugin-react';
import macrosPlugin from 'vite-plugin-babel-macros';
import { nodePolyfills } from 'vite-plugin-node-polyfills';

export default defineConfig({
    plugins: [react(), macrosPlugin(), nodePolyfills()],
    optimizeDeps: {
        esbuildOptions: {
            target: 'es2020',
            loader: {
                '.js': 'jsx',
                '.ts': 'tsx',
            },
        },
    },
    define: {
        'process.env': process.env,
    },
    build: {
        sourcemap: 'inline',
        commonjsOptions: {
            transformMixedEsModules: true,
            extensions: ['.js', '.cjs'],
        }
    },
    ...
});

After building the App and running the project, I keep getting Prism is not defined.

This is a snippet of the file inside mosaic-code-viewer that calls prismjs:

...
import ReactRendererPrism from 'prism-react-renderer/prism';
...

const g = typeof global !== 'undefined' ? global : window; // @ts-expect-error

if (!g.Prism) {
  // @ts-expect-error
  g.Prism = ReactRendererPrism;
} // @ts-expect-error


const Prism = g.Prism;


require('prismjs/components/prism-clojure');

require('prismjs/components/prism-csharp');
...

Can anyone help?

New contributor

Kareem Ibrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT