scniro / react-codemirror2

Codemirror integrated components for React
MIT License
1.66k stars 193 forks source link

Navigator is not defined when using Server-side rendering #108

Closed MatthewKosloski closed 6 years ago

MatthewKosloski commented 6 years ago

I am using the Controlled component in my GatsbyJS app.

import {Controlled as CodeMirror} from 'react-codemirror2';

import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/css/css';

When I run gatsby build, I get the following error:

  16 | // Kludges for bugs and behavior differences that can't be feature
  17 | // detected are enabled based on userAgent etc sniffing.
> 18 | var userAgent = navigator.userAgent;
     | ^
  19 | var platform = navigator.platform;
  20 |
  21 | var gecko = /gecko\/\d/i.test(userAgent);

  WebpackError: navigator is not defined

  - codemirror.js:18
    ~/codemirror/lib/codemirror.js:18:1

  - codemirror.js:11 userAgent
    ~/codemirror/lib/codemirror.js:11:1

  - codemirror.js:14 Object.<anonymous>
    ~/codemirror/lib/codemirror.js:14:2

  - css.js:6 CodeMirror.defineMode.inline
    ~/codemirror/mode/css/css.js:6:1

  - css.js:11 Object.defineProperty.value
    ~/codemirror/mode/css/css.js:11:2

  - index.tsx:12 Object.assign.i
    src/components/pages/Editor/Textarea/index.tsx:12:1

  - index.tsx:10 Object.<anonymous>
    src/components/pages/Editor/index.tsx:10:1

I noticed that in the docs, it says, "react-codemirror2 will prevent rendering in absence of navigator."

MatthewKosloski commented 6 years ago

Fixed with:

try {
    require('codemirror/mode/css/css');
} catch(e) {
    console.error(e);
}

The issue is not with React-codemirror2, rather codemirror/mode/**/*.js