question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Not working with nextjs?

See original GitHub issue

Describe the bug i try to use react-monaco-editor with next.js based on this tutorial. But all time i have a lot of errors:

Uncaught (in promise) Error: Unexpected usage
    at EditorSimpleWorker.push../node_modules/monaco-editor/esm/vs/editor/common/services/editorSimpleWorker.js.EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:540)
    at webWorker.js:54
Uncaught TypeError: Failed to construct 'URL': Invalid URL
    at push../node_modules/normalize-url/index.js.module.exports (index.js:46)
    at getReloadUrl (hotModuleReplacement.js:74)
    at hotModuleReplacement.js:92
    at NodeList.forEach (<anonymous>)
    at reloadStyle (hotModuleReplacement.js:89)
    at update (hotModuleReplacement.js:119)
    at invokeFunc (debounce.js:95)
    at trailingEdge (debounce.js:144)
    at timerExpired (debounce.js:132)
Uncaught (in promise) Error: Unexpected usage
    at EditorSimpleWorker.push../node_modules/monaco-editor/esm/vs/editor/common/services/editorSimpleWorker.js.EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:540)
    at webWorker.js:54

my code:

import React from 'react'
import PropTypes from 'prop-types'
import * as monaco from '@timkendrick/monaco-editor/dist/external'
import MonacoEditor from 'react-monaco-editor'
window.MonacoEnvironment = { baseUrl: '/monaco-editor-external' }

/**
 * @param {string} code
 * @returns {*}
 * @constructor
 */
const CodeEditor = ({code}) => {
    const options = {
        selectOnLineNumbers: true
    }

    return (
        <MonacoEditor
            // width="800"
            height="600"
            language="javascript"
            theme="vs"
            // theme="vs-dark"
            value={''}
            options={options}
            onChange={() => {}}
            editorDidMount={() => {}}
        />
    )
}

CodeEditor.propTypes = {
    code: PropTypes.string.isRequired,
}

export default CodeEditor

in server.js added:

...
    server.use(
        '/monaco-editor-external',
        express.static(`${__dirname}/node_modules/@timkendrick/monaco-editor/dist/external`)
    )
...

To Reproduce install “react-monaco-editor”: “^0.34.0” “monaco-editor”: “^0.20.0” “monaco-editor-webpack-plugin”: “^1.9.0” “@timkendrick/monaco-editor”: “0.0.9” “next”: “^9.2.1” “react”: “^16.12.0”

Expected behavior work without errors

Environment (please complete the following information):

  • OS: mac
  • Browser chrome
  • Bundler webpack

guys, please, help me. I spent for that a lot of time, i tried use with/without MonacoWebpackPlugin, with/without @stoplight/monaco, but i still got error 😦

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:3
  • Comments:27

github_iconTop GitHub Comments

19reactions
sunderlscommented, Dec 24, 2020

@subwaymatch thx, you saved my day!

@monaco-editor/react just works out of the box, no need to mess up with next.js config

18reactions
AlbinoGeekcommented, Dec 6, 2021

The following is what worked for me.

  • NO NEXT CONFIG REQUIRED
  • NO TRANSPILE MODULES
  • NO EXTERNAL REFERENCES
  • PROBABLY NO SSR EITHER (but ehh, wasn’t necessary for my use case)

package.json

// ...
  "dependencies": {
    "@monaco-editor/react": "^4.2.2",
// ... NO OTHER MONACO IMPORTS

some typescript file

import Editor from '@monaco-editor/react'
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useEffect,
  useRef
} from 'react'

//
// So... typings weren't working when I implemented Monaco, and we had to ship,
// so these placeholder types were put in place so tests passed... please fix
// these before going production. imo Monaco provides typings, they just didn't
// work when we tried them (VSCode wouldn't recognize them, tslint complained.)
//

export type MonacoEditorOptions = {
  stopRenderingLineAfter: number
}

export type MonacoEditorA = MutableRefObject<any>
export type MonacoEditorB = MutableRefObject<any>
export type MonacoTextModal = any

export type MonacoOnInitializePane = (
  monacoEditorRef: MonacoEditorA,
  editorRef: MonacoEditorB,
  model: MonacoTextModal
) => void

export type ScriptEditorProps = {
  // usage: const [code, setCode] = useState<string>('default value')
  code: string
  setCode: Dispatch<SetStateAction<string>>

  // see: https://microsoft.github.io/monaco-editor/api/modules/monaco.editor.html
  editorOptions: MonacoEditorOptions

  onInitializePane: MonacoOnInitializePane
}

//
// End of placeholder typings
//

const ScriptEditor = (props: ScriptEditorProps): JSX.Element => {
  const { code, setCode, editorOptions, onInitializePane } = props

  const monacoEditorRef = useRef<any | null>(null)
  const editorRef = useRef<any | null>(null)

  // monaco takes years to mount, so this may fire repeatedly without refs set
  useEffect(() => {
    if (monacoEditorRef?.current) {
      // again, monaco takes years to mount and load, so this may load as null
      const model: any = monacoEditorRef.current.getModels()

      if (model?.length > 0) {
        // finally, do editor's document initialization here
        onInitializePane(monacoEditorRef, editorRef, model)
      }
    }
  })

  return <Editor
    height="42.9em" // preference
    language="go"   // preference
    onChange={(value, _event) => {
      setCode(value)
    }}
    onMount={(editor, monaco) => {
      monacoEditorRef.current = monaco.editor
      editorRef.current = editor
    }}
    options={editorOptions}
    theme="vs-dark" // preference
    value={code}
    width="60em"    // preference
  />
}

export default ScriptEditor

example usage

import ScriptEditor, { MonacoOnInitializePane } from '../components/ScriptEditor'
import { useState } from 'react'

const Index = () => {
  const [code, setCode] = useState<string>(`
  // Hello, World!
  const foo = 1 + 1
`)

  const onInitializePane: MonacoOnInitializePane = (
    monacoEditorRef,
    editorRef,
    model
  ) => {
    editorRef.current.setScrollTop(1)
    editorRef.current.setPosition({
      lineNumber: 2,
      column: 0,
    })
    editorRef.current.focus()
    monacoEditorRef.current.setModelMarkers(model[0], 'owner', null)
  }

  return <ScriptEditor
    code={code}
    setCode={setCode}
    editorOptions={{
      stopRenderingLineAfter: 1000,
    }}
    onInitializePane={onInitializePane}
  />
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

javascript - Tailwindcss not working with next.js; what is wrong ...
Considering that there's no such issue opened at Tailwind, I guess the problem has something to do with Next.js not purging properly.
Read more >
TailwindCSS not working in NX NextJS project. #8355 - GitHub
Current Behavior Following the egghead tutorial for a NextJS project with a new nx-workspace, installing Tailwind is not working.
Read more >
Debugging Tailwind CSS and Next.js - LogRocket Blog
Common issues with Tailwind CSS and Next.js · Not having the Tailwind directives in the main CSS file · Not assigning the CSS...
Read more >
module-not-found - Next.js
The module you're trying to import uses Node.js specific modules, for example dns , outside of getStaticProps / getStaticPaths / getServerSideProps. Possible ...
Read more >
How to Set Up Next.js With Tailwind - Jake Prins
You can save yourself some time by using Next.js, a React framework that provides a solution to all of these problems above. If...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Hashnode Post

No results found