mantine icon indicating copy to clipboard operation
mantine copied to clipboard

[@mantine/code-highlight] Attempt on reducing bundle size

Open ibedwi opened this issue 1 year ago • 2 comments

Description

This is an attempt to reduce the size of code-highlight.

Probably address https://github.com/mantinedev/mantine/issues/4879, https://github.com/mantinedev/mantine/issues/5021

Approach

Instead of install highlight.js as the library's dependencies, it's installed as peerDependencies. The project that use code highlight library must install highlight.js as its dependencies and pass it to this library via HiglightProvider

// /the-project/page.tsx
import { CodeHighlight, HighlightProvider } from "@mantine/code-highlight-lite";

// Only import the core module
import hljs from "highlight.js/lib/core";

// Only registere the used languages
hljs.registerLanguage(
  "plaintext",
  require("highlight.js/lib/languages/plaintext")
);
hljs.registerLanguage(
  "javascript",
  require("highlight.js/lib/languages/javascript")
);
hljs.registerLanguage(
  "typescript",
  require("highlight.js/lib/languages/typescript")
);

// Create example typescript code
const exampleCode = "...";

export default function Home() {
  return (
    // pass hljs as props to the provider
    <HighlightProvider highlightInstance={hljs}>
        <CodeHighlight code={exampleCode} language="typescript" />
    </HighlightProvider>
  );
}

Result

This approach tested using Next.js 14.0.2 (app router) and Webpack Bundle Analyzer. The highlight.js's chunk is very small and only include the registered language:

Stat size: 120.91 KB
Parsed size: 38.16 KB
Gzipped size: 12.23 KB
CleanShot 2023-11-12 at 13 53 48@2x

Demo Project

See the demo project here

ibedwi avatar Nov 12 '23 06:11 ibedwi

Hi @ibedwi, thanks for the PR! I would rather not maintain two separate versions of the same package. It also seems that it is not possible to solve this issue without breaking changes. I'll keep this PR opened until 8.0 is out for reference. Now the PR cannot be merged.

rtivital avatar Nov 12 '23 12:11 rtivital

Hi @rtivital ! I agree to not maintain two separate versions of the same package, since it serves the same purpose.

It also seems that it is not possible to solve this issue without breaking changes.

Yeap! Since this approach exclude highlight.js from the package, it definitely introduce breaking changes.

I'll keep this PR opened until 8.0 is out for reference. Now the PR cannot be merged.

Thanks for considering this PR! I would love to contribute! Feel free to ping me 😁

ibedwi avatar Nov 12 '23 12:11 ibedwi