tailwind-editor icon indicating copy to clipboard operation
tailwind-editor copied to clipboard

window is not defined

Open lucasyoboy opened this issue 1 year ago • 5 comments

ReferenceError: window is not defined at \node_modules\tailwind-editor\src\index.js:1:14 at instantiateModule (/node_modules/vite/dist/node/chunks/dep-cNe07EU9.js:55058:15)

lucasyoboy avatar May 03 '24 14:05 lucasyoboy

Getting the same error.

TopherTimeMachine avatar May 14 '24 04:05 TopherTimeMachine

If using in sveltekit, you may need to dynamically import this module depending on the "browser" variable. SSR will attempt to run this code in a server-context of which "window" is going to be undefined.

E.g.,

import { browser } from '$app/environment';

onMount(() => {
  loadEditor();
});

const loadEditor = async () => {
  if (browser) {
    const Editor = (await import("@tailwind-editor")).default;
  }
};

benbrunyee avatar May 15 '24 10:05 benbrunyee

No, that doesn't work. Have you tried it?

lucasyoboy avatar May 25 '24 17:05 lucasyoboy

That’s how it’s working for my SvelteKit site:

	const loadEditor = async () => {
		// Only load the editor if we are in a browser environment
		if (browser) {
			const EditorJS = (await import('@editorjs/editorjs')).default;
			const Header = (await import('@editorjs/header')).default;
			// @ts-ignore
			const List = (await import('@editorjs/list')).default;

			editor = new EditorJS({
				holder: 'editor-js',
				autofocus: true,
				tools: {
					// @ts-ignore
					header: { class: Header, config: { levels: [1, 2, 3, 4] } },
					list: List
				},
				inlineToolbar: ['link', 'bold', 'italic']
			});
		}
	};

Seems to be working fine for me - no issues as of yet. I’m running with: "@editorjs/editorjs": "^2.29.1"

benbrunyee avatar May 25 '24 17:05 benbrunyee

If you are running any sort of SSR (Server Side Rendering), then the JavaScript will try and run server side.

You have to wrap the client-side code in the if ( window !== undefined ) {} or if ( browser ) {}, where "browser" function is avaiable in SvleteKit as a helper.

This will ensure that that code will not get run server side.

The reason I suspect it works for some people and not others, is because some people run SvelteKit as SSG or CSR modes for some routes (or all routes) but everyone else might be running SSR mode. SvelteKit is unique in that it lets you define modes per route, so this isn't obvious for a lot of people.

maietta avatar May 25 '24 17:05 maietta