Giter Club home page Giter Club logo

Comments (5)

medihack avatar medihack commented on August 22, 2024 1

Thanks so much for the help and the comprehensible explanations! I tried your solution and it works perfectly. The only thing that I still have to set is customLanguages of monaco-webpack-editor-plugin as otherwise, it seems the workers of monaco-yaml are not found correctly (error trace below).

editorSimpleWorker.js?7713:450 Uncaught (in promise) Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js?7713:450)
    at eval (webWorker.js?b9e1:38)
loadForeignModule @ editorSimpleWorker.js?7713:450
eval @ webWorker.js?b9e1:38
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?3be2:13
_next @ asyncToGenerator.js?3be2:25
eval @ asyncToGenerator.js?3be2:32
eval @ asyncToGenerator.js?3be2:21
doValidate @ monaco.contribution.js?c770:54
onModelAdd @ monaco.contribution.js?c770:73
fire @ event.js?e6ce:428
createModel @ modelServiceImpl.js?6f79:324
doCreateModel @ standaloneCodeEditor.js?2969:323
createTextModel @ standaloneCodeEditor.js?2969:317
StandaloneEditor @ standaloneCodeEditor.js?2969:180
eval @ standaloneEditor.js?f9e7:62
withAllStandaloneServices @ standaloneEditor.js?f9e7:49
create @ standaloneEditor.js?f9e7:61
MonacoEditor.initMonaco @ editor.js?5228:110
MonacoEditor.componentDidMount @ editor.js?5228:53
commitLayoutEffectOnFiber @ react-dom.development.js?a814:22361
commitLayoutMountEffects_complete @ react-dom.development.js?a814:23709
commitLayoutEffects_begin @ react-dom.development.js?a814:23695
commitLayoutEffects @ react-dom.development.js?a814:23633
commitRootImpl @ react-dom.development.js?a814:25694
commitRoot @ react-dom.development.js?a814:25559
finishConcurrentRender @ react-dom.development.js?a814:24919
performConcurrentWorkOnRoot @ react-dom.development.js?a814:24797
workLoop @ scheduler.development.js?e22e:253
flushWork @ scheduler.development.js?e22e:226
performWorkUntilDeadline @ scheduler.development.js?e22e:516
errors.js?5b96:8 Uncaught Error: Unexpected usage

Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js?7713:450)
    at eval (webWorker.js?b9e1:38)
    at eval (errors.js?5b96:8)
eval @ errors.js?5b96:8
setTimeout (async)
ErrorHandler.unexpectedErrorHandler @ errors.js?5b96:6
onUnexpectedExternalError @ errors.js?5b96:25
onUnexpectedExternalError @ errors.js?5b96:39
Promise.then (async)
eval @ getLinks.js?6430:123
getLinks @ getLinks.js?6430:122
eval @ links.js?133f:184
createCancelablePromise @ async.js?91a0:22
_callee$ @ links.js?133f:184
tryCatch @ runtime.js?df26:63
invoke @ runtime.js?df26:294
eval @ runtime.js?df26:119
eval @ links.js?133f:20
__awaiter @ links.js?133f:16
beginCompute @ links.js?133f:172
onModelChanged @ links.js?133f:162
eval @ links.js?133f:145
fire @ event.js?e6ce:428
StandaloneEditor @ standaloneCodeEditor.js?2969:193
eval @ standaloneEditor.js?f9e7:62
withAllStandaloneServices @ standaloneEditor.js?f9e7:49
create @ standaloneEditor.js?f9e7:61
MonacoEditor.initMonaco @ editor.js?5228:110
MonacoEditor.componentDidMount @ editor.js?5228:53
commitLayoutEffectOnFiber @ react-dom.development.js?a814:22361
commitLayoutMountEffects_complete @ react-dom.development.js?a814:23709
commitLayoutEffects_begin @ react-dom.development.js?a814:23695
commitLayoutEffects @ react-dom.development.js?a814:23633
commitRootImpl @ react-dom.development.js?a814:25694
commitRoot @ react-dom.development.js?a814:25559
finishConcurrentRender @ react-dom.development.js?a814:24919
performConcurrentWorkOnRoot @ react-dom.development.js?a814:24797
workLoop @ scheduler.development.js?e22e:253
flushWork @ scheduler.development.js?e22e:226
performWorkUntilDeadline @ scheduler.development.js?e22e:516

from monaco-yaml.

remcohaszing avatar remcohaszing commented on August 22, 2024

I noticed you’re using monaco-webpack-plugin. I recently found one project which uses monaco-yaml combined with monaco-webpack-plugin as well. Does this help you?

from monaco-yaml.

medihack avatar medihack commented on August 22, 2024

Thanks, I guess this helps with a problem that would occur (loading the correct worker) after my problem is solved :-) The current error occurs when calling setDiagnosticsOptions. Maybe it's more a problem of getting it to work with react-monaco-editor, not sure.

import { dynamic } from "blitz"
import { setDiagnosticsOptions } from "monaco-yaml"
import { ComponentType } from "react"
import { MonacoEditorProps } from "react-monaco-editor"

const MonacoEditor: ComponentType<MonacoEditorProps> = dynamic(
  () => import("react-monaco-editor"),
  { ssr: false }
)

export const ModuleEditor = () => {
  return (
    <div>
      <MonacoEditor
        height={300}
        language="yaml"
        editorWillMount={() => {
          setDiagnosticsOptions({
            enableSchemaRequest: true,
            hover: true,
            completion: true,
            validate: true,
            format: true,
            schemas: [
              {
                uri: "http://myserver/bar-schema.json",
                schema: {
                  type: "object",
                  properties: {
                    q1: {
                      enum: ["x1", "x2"],
                    },
                  },
                },
              },
            ],
          })
        }}
      />
    </div>
  )
}

from monaco-yaml.

medihack avatar medihack commented on August 22, 2024

Ok, it seems I found a solution (even if I don't understand all details ;-))

Maybe it will help someone else or there is room for improvement:

// blitz.config.ts (cause I use Blitz.js, but next.config.js should work similarly)

import { sessionMiddleware, simpleRolesIsAuthorized } from "blitz"
import bundleAnalyzer from "@next/bundle-analyzer"
import nextTranspileModules from "next-transpile-modules"
import MonacoWebpackPlugin from "monaco-editor-webpack-plugin"

const enableBundleAnalyzer = process.env.npm_lifecycle_event === "build"

const withTM = nextTranspileModules(["monaco-editor", "monaco-yaml"])

const withBundleAnalyzer = bundleAnalyzer({
  enabled: enableBundleAnalyzer,
})

module.exports = withTM(
  withBundleAnalyzer({
    webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
      // Allows the modules to find their module name during build time
      config.node = {
        ...config.node,
        __dirname: true,
      }
      config.plugins.push(
        new MonacoWebpackPlugin({
          languages: ["yaml"],
          features: [],
          filename: "static/[name].worker.js",
          customLanguages: [
            {
              label: "yaml",
              entry: "/workspace/myproject/node_modules/monaco-yaml/lib/esm/monaco.contribution",
              worker: {
                id: "vs/language/yaml/yamlWorker",
                entry: "/workspace/myproject/node_modules/monaco-yaml/lib/esm/yaml.worker.js",
              },
            },
          ],
        })
      )
      return config
    },
  })
)
// my editor component

import { dynamic } from "blitz"
import { setDiagnosticsOptions as _ } from "monaco-yaml"

const MonacoEditor = dynamic(() => import("react-monaco-editor"), { ssr: false })

export const ModuleEditor = () => {
  return (
    <div>
      <MonacoEditor
        height={300}
        language="yaml"
        editorWillMount={(monaco) => {
          monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions({
            enableSchemaRequest: true,
            hover: true,
            completion: true,
            validate: true,
            format: true,
            schemas: [
              {
                // Id of the first schema
                uri: "http://myserver/bar-schema.json",
                schema: {
                  type: "object",
                  properties: {
                    q1: {
                      enum: ["x1", "x2"],
                    },
                  },
                },
              },
            ],
          })
        }}
      />
    </div>
  )
}

yaml seems to be attached to monaco.languages by the MonacoWebpackPlugin loader. And setDiagnosticsOptions must be called by monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions and not directly. I still have to import it (import { setDiagnosticsOptions as _ } from "monaco-yaml", but only to satisfy the Typescript god as otherwise monaco.languages.yaml will report a TS error (this was the most cumbersome thing about this solution).

Hope this helps.

from monaco-yaml.

remcohaszing avatar remcohaszing commented on August 22, 2024

Thanks for showing your solution! I hope this helps other users as well.

I would like to explain what I think is going on based on your solution.

You’re importing react-monaco-editor dynamically, but monaco-yaml statically. Both import monaco-editor. As a result, monaco-editor is included twice in your bundle, once in your main bundle and once in the chunk generated by the react-monaco-editor import. Because of this monaco-yaml is applied to another instance of monaco-editor than the one of react-monaco-editor, causing it to simply not work. This also increased your build output size by a lot.

monaco-editor-webpack-plugin makes sure that monaco-yaml is also included with the react-monaco-editor chunk, which causes monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions to be available. I would like to remove this API in a major release though, so I recommend not to use this.

Instead of using import { setDiagnosticsOptions as _ } from "monaco-yaml" to please the TypeScript gods, you could also add monaco-yaml to the types array in tsconfig.json. Although this isn’t necessary with the solution below.

Instead of dynamically importing react-monaco-editor, you could create a small wrapper file which configures both monaco-yaml and react-monaco-editor.

// monaco-setup.ts
import { setDiagnosticsOptions } from 'monaco-yaml';

export { default } from 'react-monaco-editor';

setDiagnosticsOptions({
  enableSchemaRequest: true,
  hover: true,
  completion: true,
  validate: true,
  format: true,
  schemas: [
    {
      // Id of the first schema
      uri: "http://myserver/bar-schema.json",
      schema: {
        type: "object",
        properties: {
          q1: {
            enum: ["x1", "x2"],
          },
        },
      },
    },
  ],
})

Then inside your editor component:

// my editor component

import { dynamic } from "blitz"

const MonacoEditor = dynamic(() => import("./monaco-setup.ts"), { ssr: false })

export const ModuleEditor = () => {
  return (
    <div>
      <MonacoEditor
        height={300}
        language="yaml"
      />
    </div>
  )
}

Now you could set the entry for custom language setup in monaco-webpack-editor-plugin to undefined.

from monaco-yaml.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.