RDKit.js

repository·master·Indexed 42 days ago

https://github.com/rdkit/rdkit-js

The official JavaScript distribution of the RDKit cheminformatics library, powered by WebAssembly (WASM). It enables complex chemical informatics tasks, such as parsing SMILES strings and calculating molecular descriptors, directly in the browser or Node.js.

Tokens
1.8K
Snippets
6
Records
7
Agent score
4%

What's inside RDKit.js

  1. Best practices and performance tips for RDKit.js

    master

    To ensure a smooth user experience and efficient memory management, follow these tips:

    • Offload heavy work: Run the RDKit module inside a Web Worker to prevent blocking the main UI thread during intensive cheminformatics computations.
    • Memory Management: Always call mol.delete() on molecule objects once they are no longer needed to prevent memory leaks.
    • SVG Styling: To make molecule SVG renders have a transparent background, use the following CSS:
      .molecule-structure-svg svg rect:first-of-type { fill: transparent !important; }
    • Exception Handling: The package is compiled with Emscripten -fwasm-exceptions, supporting WebAssembly.Exception.
  2. Install @rdkit/rdkit

    master

    You can install RDKit.js using npm, yarn, or pnpm, or include it directly via a CDN script tag.

    Using Package Managers

    npm i @rdkit/rdkit
    # or
    yarn add @rdkit/rdkit
    # or
    pnpm i @rdkit/rdkit

    Using CDN

    <script src="https://unpkg.com/@rdkit/rdkit/dist/RDKit_minimal.js"></script>
    npm i @rdkit/rdkit
  3. Configure Next.js for RDKit.js

    master

    To use RDKit.js in a Next.js project, you must configure next.config.ts to handle the WASM module and prevent issues with Node.js-specific modules in the browser.

    1. Add @rdkit/rdkit to serverExternalPackages to ensure it is treated as an external package on the server.
    2. Use turbopack.resolveAlias to map RDKit_minimal.wasm to the correct path in node_modules.
    3. Provide a dummy stub for the fs module to prevent Emscripten's Node probe from failing in the browser bundle.
    // next.config.ts
    import type { NextConfig } from "next";
    
    const nextConfig: NextConfig = {
      serverExternalPackages: ["@rdkit/rdkit"],
      turbopack: {
        resolveAlias: {
          "RDKit_minimal.wasm":
            "./node_modules/@rdkit/rdkit/dist/RDKit_minimal.wasm",
          fs: { browser: "./src/lib/dummy.ts" },
        },
      },
    };
    
    export default nextConfig;
  4. Basic molecule manipulation with RDKit.js

    master

    Once initialized, you can use the RDKit object to parse SMILES strings into molecule objects. Common operations include retrieving SMILES, atom counts, and descriptors.

    Important: Always call mol.delete() when you are finished with a molecule object to manually free the memory used by the WASM module.

    const RDKit = await initRDKitModule();
    console.log(RDKit.version());
    
    const mol = RDKit.get_mol("CCO");
    if (!mol) throw new Error("Failed to parse SMILES");
    
    console.log(mol.get_smiles());
    console.log(mol.get_num_atoms());
    console.log(JSON.parse(mol.get_descriptors()).amw);
    
    // Free memory
    mol.delete();
  5. Use RDKit.js in a Next.js API Route

    master

    RDKit.js can be used directly in Next.js Server Components or API routes. Since these run in a Node.js environment, you can call initRDKitModule() without providing a locateFile option.

    Example of an API route returning molecular data as JSON:

    // src/app/api/rdkit/route.ts
    import { NextResponse } from "next/server";
    import initRDKitModule from "@rdkit/rdkit";
    
    export async function GET() {
      const RDKit = await initRDKitModule();
      const mol = RDKit.get_mol("CCO");
      if (!mol) {
        return NextResponse.json(
          { error: "Failed to parse SMILES" },
          { status: 500 },
        );
      }
    
      const payload = {
        version: RDKit.version(),
        smiles: mol.get_smiles(),
        atoms: mol.get_num_atoms(),
        amw: JSON.parse(mol.get_descriptors()).amw,
      };
      mol.delete();
    
      return NextResponse.json(payload);
    }
  6. Use RDKit.js in a Next.js Client Component

    master

    When using RDKit.js on the client side, you must use the `

    // src/app/rdkit-demo.tsx
    "use client";
    
    import { useEffect, useState } from "react";
    import initRDKitModule from "@rdkit/rdkit";
    
    const wasmUrl = new URL("RDKit_minimal.wasm", import.meta.url).href;
    
    export default function RdkitDemo() {
      const [text, setText] = useState("Loading…");
    
      useEffect(() => {
        initRDKitModule({ locateFile: () => wasmUrl }).then((RDKit) => {
          const lines = [`RDKit version: ${RDKit.version()}`];
          const mol = RDKit.get_mol("CCO");
          if (!mol) {
            lines.push("Failed to parse SMILES");
          } else {
            lines.push(`SMILES: ${mol.get_smiles()}`);
            lines.push(`Atoms: ${mol.get_num_atoms()}`);
            lines.push(`MW: ${JSON.parse(mol.get_descriptors()).amw}`);
            mol.delete();
          }
          setText(lines.join("\n"));
        });
      }, []);
    
      return <pre>{text}</pre>;
    }
  7. Initialize the RDKit WASM module

    master

    The RDKit library is loaded asynchronously via initRDKitModule(). This function returns a Promise that resolves to the RDKit library object.

    Note that when using bundlers, you may encounter issues where the .wasm file is not fetchable or is separated from the glue JS. Additionally, some static analysis tools might flag node: function calls in the .js file, even though they are only executed in a Node.js environment.

    const RDKit = await initRDKitModule();
    console.log("RDKit version:", RDKit.version());