rollup icon indicating copy to clipboard operation
rollup copied to clipboard

Run the library in server-side environment (Next.js)

Open rm116 opened this issue 2 years ago • 6 comments

Hello, I have a problem using my library (packed by rollup) in my Next/React application, I have this error : ReferenceError: window is not defined

Call Stack eval webpack-internal:///../library/lib/cjs/index.js (23014:15)

And the code in that line is : var browser = window.DOMPurify || (window.DOMPurify = requirePurify().default || requirePurify());

it's due to Next.js is trying to server-side render my library but can't find the "window" reference, here is my rollup config file, how can I make it rendable in next.js :

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
import json from "@rollup/plugin-json";
import postcss from "rollup-plugin-postcss";
import terser from '@rollup/plugin-terser';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';

const packageJson = require("./package.json");

export default [
  {
    input: "src/index.ts",
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(),
      resolve({
        browser: true
      }),
      commonjs(),
      typescript({ tsconfig: "./tsconfig.json" }),
      json(),
      postcss(),
      terser()
    ],
  },
  {
    input: "lib/esm/types/index.d.ts",
    output: [
      {
        file: 'lib/index.d.ts',
        format: 'esm',
      }
    ],
    plugins: [dts()],
    external: ['react', 'react-dom', /\.css$/]
  },
];

rm116 avatar Jun 19 '23 13:06 rm116

The issue needs to be fixed in your code. Wherever you're using browser-specific APIs, you need to verify if they even exist before accessing them

brc-dd avatar Jun 19 '23 14:06 brc-dd

@brc-dd do you mean the "library" code or the consuming "application" code ?

rm116 avatar Jun 19 '23 19:06 rm116

The library code.

brc-dd avatar Jun 19 '23 19:06 brc-dd

I don't have that in my code, it's rollup who is generating this line : var browser = window.DOMPurify || (window.DOMPurify = requirePurify().default || requirePurify());

in lib/cjs/index.js

rm116 avatar Jun 19 '23 19:06 rm116

Can you share a minimal example that we can reproduce (preferably in the form of a repo link)? It is likely that one of your dependency has that part of code 👀

brc-dd avatar Jun 19 '23 19:06 brc-dd

@rm116 Did you ever get this resolved? I'm running into the same issue.

mikeriley131 avatar Nov 10 '23 17:11 mikeriley131