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

How to import this library in a create-react-app?

Open kasperpeulen opened this issue 8 years ago β€’ 16 comments

I'm using from https://github.com/facebookincubator/create-react-app:

So far, I haven't had problems importing npm modules with the following syntax: import _ from 'lodash'

However, I couldn't get this library to work in this setup. This seems like a super powerful editor, just can not get it to work.

kasperpeulen avatar Jul 30 '16 11:07 kasperpeulen

An old issue, but with a lot of thumbs up. Someone has done the work of wrapping the monaco editor in a react component: https://www.npmjs.com/package/@types/react-monaco-editor

Note that there are some issues with this implementation. To make it work myself, I included

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.1/require.min.js"></script>
<script>
    require.config({
      paths: { 'vs': './vs' }
    })
</script>

in the public/index.html file of my create-react-app project. I also placed the 'vs' folder from the monaco node module in my public folder (see that the require.config() function is looking for it. The files in this folder needed to be served from my own site rather than a CDN (as suggested by the react-monaco-editor readme) in order to avoid browsers complaining about running 'foreign' webworkers.

Good luck. I had more trouble than I expected setting this up, but it's going swimmingly now.

NiloCK avatar Oct 02 '17 01:10 NiloCK

@NiloCK you saved me from giving up! Thanks!

YairoR avatar Oct 25 '17 21:10 YairoR

Now that monaco supports esm modules (thanks!), i was really hoping i'll be able to use the monaco-editor npm package in a create-react-app application (since the later is using webpack under the hood).

Unfortunately, monaco-editor-smpale seem to suggest i need to configure webpack with plugins, which is not possible in create-react-app without ejecting.

Did anyone successfully import monaco-editor package in create-react-app without ejecting and without doing weird stuff like loading monaco's loader.js?

lidermanrony avatar Apr 01 '18 12:04 lidermanrony

Bump. Also wondering the above question.

nico-bellante avatar May 20 '18 04:05 nico-bellante

I stumbled upon the issue of getting Monaco up and running with create-react-app again this evening and dug up a solution that I've used before which circumvents copying files to the public folder – so I decided to do a small write up, you can find it here:

https://medium.com/@haugboelle/short-guide-to-using-monaco-with-create-react-app-26a1acad8ebe

henrikhaugboelle avatar May 28 '18 20:05 henrikhaugboelle

Hope Microsoft release monaco-editor-react package offically πŸ‘

liudonghua123 avatar Nov 26 '18 01:11 liudonghua123

@kasperpeulen, after tried a lot of method mentioned here, I found a elegant way by replace react-scripts with react-app-rewired, add a config-overrides.js file contains

/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function override(config, env) {
  if (!config.plugins) {
    config.plugins = [];
  }
  config.plugins.push(
    new MonacoWebpackPlugin()
  );
  return config;
}

The full functional demo can be found on https://github.com/liudonghua123/create-react-app-monaco-editor

liudonghua123 avatar Nov 26 '18 02:11 liudonghua123

I use it this way. seems working fine currently.. (copy vs source directory to public/js/monaco)

      window.require = { paths: { 'vs': `${_url_origin}${prefix}/js/monaco/vs` } };
       
        $('head').append($('<link rel="stylesheet" type="text/css" />')
            .attr('href', `${_url_origin}${prefix}/js/monaco/vs/editor/editor.main.css`));

        $.when(
            
            $.getScript( `${_url_origin}${prefix}/js/monaco/vs/language/typescript/tsMode.js` ),
            $.getScript( `${_url_origin}${prefix}/js/monaco/vs/basic-languages/javascript/javascript.js` ),
            $.getScript( `${_url_origin}${prefix}/js/monaco/vs/language/typescript/tsWorker.js` ),

            $.getScript(  `${_url_origin}${prefix}/js/monaco/vs/loader.js` ),
            $.getScript( `${_url_origin}${prefix}/js/monaco/vs/editor/editor.main.nls.js` ),
            $.getScript( `${_url_origin}${prefix}/js/monaco/vs/editor/editor.main.js` ),
            $.Deferred(function( deferred ){
                console.log('Deferred')
                $( deferred.resolve );
                setTimeout(() => {
                    
                    callback && callback()
                }, 10000);
            })
        ).done(function(){
            debugger;
            // TODO done function not worked
            console.log('done done done ')
            //place your code here, the scripts are all loaded
            // callback && callback()
        });

wufeng87 avatar Dec 19 '18 02:12 wufeng87

@monaco-editor/react

I think it will help you guys.

I faced this issue about 2 years ago. I wrote a wrapper, for monaco to use it with an application powered by create-react-app. And use that solution in many projects. Now I publish it. Basically, it’s a monaco editor wrapper for painless integration with React applications without the need of webpack (or another module bundler) configuration files.

suren-atoyan avatar Jun 24 '19 07:06 suren-atoyan

For anyone wanting to use the react-monaco-editor library, this scripts-version fork includes everything you need by default.

JS-only:

npx create-react-app --scripts-version=@bitauth/react-scripts-bitauth-ide my-app

Typescript:

npx create-react-app --typescript --scripts-version=@bitauth/react-scripts-bitauth-ide my-app

And you can see an example of it working with a custom theme, custom language, range markers (underlining errors), hover providers, and autocompletion providers in bitauth-ide.

bitjson avatar Nov 07 '19 04:11 bitjson

This is the cleanest setup I was able to come up with. It's not ideal since Monaco is now outside of npm, but it got the job done for my needs.

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/editor/editor.main.css">
  </head>
  <body>
    <div id="root"></div>
    <script>var require={paths:{'vs':'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs'}};</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/loader.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/editor/editor.main.nls.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.20.0/min/vs/editor/editor.main.js"></script>
  </body>
</html>

Then

import React from 'react'

export default function Monaco({ config, onEditor }) {
  const elem = React.useRef()
  const monaco = React.useRef(window.monaco)
  const [editor, setEditor] = React.useState()

  React.useEffect(() => {
    if (elem.current && monaco.current && !editor) {
      const newEditor = monaco.current.editor.create(elem.current, config)
      setEditor(newEditor)
    }
  }, [config, elem, monaco, editor])

  React.useEffect(() => {
    if (editor) {
      onEditor?.(editor)
    }
  }, [editor, onEditor])

  return <div ref={elem} />
}

kellengreen avatar Mar 02 '20 22:03 kellengreen

So I stumbled on this post in search of a way to get syntax highlighting and autocomplete working with Monaco Editor. I tried a few of the solutions above and was not satisfied with the result. So I took a different approach....

  • Made new app from CRA (create react app).
  • Added create-react-app-rewired (here)
    • yarn add react-app-rewired
    • Created file "config-overrides.js" in project root dir.
    • Updated the 'scripts' section of package.json according to create-react-app-rewired (side note, the commented out lines are there for display, don't copy/paste since comments dont work in JSON)...
  /* package.json */

"scripts": {
    // "start": "react-scripts start",
    "start": "react-app-rewired start",
    // "build": "react-scripts build",
    "build": "react-app-rewired build",
    // "test": "react-scripts test --env=jsdom",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject" // dont change eject
}
  • Added Monaco Editor Webpack Loader Plugin (here)
    • yarn add monaco-editor-webpack-plugin
    • Added the following to the config-overrides file...
/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function override(config, env) {
    config.plugins = [
        ...config.plugins,
        new MonacoWebpackPlugin()
    ]

    return config;
}

Syntax highlighting and auto complete now works. I hope this helps someone out there πŸŽ‰

jbalesteri avatar Mar 03 '20 17:03 jbalesteri

Yet another update of @monaco-editor/react

suren-atoyan avatar Aug 20 '20 13:08 suren-atoyan

I'm able to use monaco 0.30.1 in a CRA app without using react-app-rewired or monaco-editor-webpack-plugin and intellisense/syntax highlighting for my custom language is working fine but I am getting a webworker error when running

Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/microsoft/monaco-editor#faq
node_modules/monaco-editor/esm/vs/base/common/worker/simpleWorker.js:20

Uncaught SyntaxError: Unexpected token '<'
node_modules/monaco-editor/esm/vs/base/common/worker/simpleWorker.js:22

I did try adding react-app-rewired and monaco-editor-webpack-plugin as per @jbalesteri but it didn't fix this issue. I also tried using craco per this example - https://github.com/suren-atoyan/monaco-react/issues/68#issuecomment-883392669 ( I'm not using monaco-react but thought it might work ). And ideas on what else to try?

qsc-jhndnn avatar Dec 06 '21 23:12 qsc-jhndnn

So I stumbled on this post in search of a way to get syntax highlighting and autocomplete working with Monaco Editor. I tried a few of the solutions above and was not satisfied with the result. So I took a different approach....

  • Made new app from CRA (create react app).

  • Added create-react-app-rewired (here)

    • yarn add react-app-rewired
    • Created file "config-overrides.js" in project root dir.
    • Updated the 'scripts' section of package.json according to create-react-app-rewired (side note, the commented out lines are there for display, don't copy/paste since comments dont work in JSON)...
  /* package.json */

"scripts": {
    // "start": "react-scripts start",
    "start": "react-app-rewired start",
    // "build": "react-scripts build",
    "build": "react-app-rewired build",
    // "test": "react-scripts test --env=jsdom",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject" // dont change eject
}
  • Added Monaco Editor Webpack Loader Plugin (here)

    • yarn add monaco-editor-webpack-plugin
    • Added the following to the config-overrides file...
/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function override(config, env) {
    config.plugins = [
        ...config.plugins,
        new MonacoWebpackPlugin()
    ]

    return config;
}

Syntax highlighting and auto complete now works. I hope this helps someone out there πŸŽ‰

thank u so much!!!! u save my life!

LinYUAN-code avatar Apr 07 '22 03:04 LinYUAN-code

Trying to bundle monaco editor into my app using react-app-rewired and webpack. When trying to deploy to disconnected environment - I'm getting 404 on the file: https://cdn.jsdelivr.net/npm/[email protected]/min/vs/loader.js

When I deploy to an environment which is connected to the internet, I see all the files are pulled from jsdelivr and not from my bundle. I tried to set the publicPath to '/' or remove it totally, but the behavior is the same. Does anyone has any idea?

Here is my configuration of config-overrides.js:

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function override(config, env) {
    config.plugins = [
        ...config.plugins,
        new MonacoWebpackPlugin({
          languages:['sql'],
          publicPath: "/build/"
      })
    ]

    return config;
}

yuval-illumex avatar Aug 30 '22 14:08 yuval-illumex

After a lot of testing and playing around this was the ultimate answer, which I was looking for: https://github.com/microsoft/monaco-editor/issues/2605#issue-962590804

  • Only CRA without overrides
  • @monaco-editor/react
  • Monaco is part of my bundle (no CDN)
  • Lazy loading with React.lazy & React.Suspense
import Editor, { loader } from '@monaco-editor/react';

window.MonacoEnvironment = {
  getWorker(moduleId, label): Promise<Worker> | Worker {
    // see linked comment
  },
};

loader.config({ monaco });

const MonacoEditorFactory: React.FC = () => {
  return <Editor />;
}
const MonacoEditorFactory = React.lazy(() => import('controls/monaco-editor/DummyMonaco'));

export const MonacoEditor: React.FC = () => {
  return (
    <div>
      <React.Suspense fallback={<span>Loading...</span>}>
        <MonacoEditorFactory />
      </React.Suspense>
    </div>
  );
}

cbn-falias avatar Jan 30 '23 12:01 cbn-falias

We closed this issue because we don't plan to address it in the foreseeable future. If you disagree and feel that this issue is crucial: we are happy to listen and to reconsider.

If you wonder what we are up to, please see our roadmap and issue reporting guidelines.

Thanks for your understanding, and happy coding!

hediet avatar Feb 24 '23 10:02 hediet

What about updating the webpack samples? I think that the outdated examples are the main reason why this topic still exists and people keep coming back here.

Knowing that one can use new Worker(..., import.meta.url)); instead of adding them as entry-points is such a game changer.

cbn-falias avatar Feb 24 '23 11:02 cbn-falias

We'd be open for a PR! We got the webpack examples as community contribution and are no webpack experts ourselves.

hediet avatar Mar 07 '23 10:03 hediet