Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
kasperpeulen opened this issue Jul 30, 2016 · 20 comments
Closed

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

kasperpeulen opened this issue Jul 30, 2016 · 20 comments
Labels
feature-request Request for new features or functionality integration integration-react
Milestone

Comments

@kasperpeulen
Copy link

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.

@NiloCK
Copy link

NiloCK commented Oct 2, 2017

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.

@YairoR
Copy link

YairoR commented Oct 25, 2017

@NiloCK you saved me from giving up! Thanks!

@lidermanrony
Copy link

lidermanrony commented Apr 1, 2018

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?

@nico-bellante
Copy link

Bump.
Also wondering the above question.

@henrikhaugboelle
Copy link

henrikhaugboelle commented May 28, 2018

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

@liudonghua123
Copy link

Hope Microsoft release monaco-editor-react package offically 👍

liudonghua123 added a commit to liudonghua123/create-react-app-monaco-editor that referenced this issue Nov 26, 2018
@liudonghua123
Copy link

@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

@wufeng87
Copy link

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()
        });

@suren-atoyan
Copy link

@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.

@bitjson
Copy link

bitjson commented Nov 7, 2019

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.

@alexdima alexdima added integration-react feature-request Request for new features or functionality labels Dec 12, 2019
@alexdima alexdima added this to the Backlog milestone Dec 12, 2019
@kellengreen
Copy link

kellengreen commented Mar 2, 2020

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} />
}

@jbalesteri
Copy link

jbalesteri commented Mar 3, 2020

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 🎉

zastrowm added a commit to zastrowm/friendly-engine that referenced this issue Aug 6, 2020
See microsoft/monaco-editor#82
We copy it locally and then hack the loader to load it
@suren-atoyan
Copy link

Yet another update of @monaco-editor/react

arlosi pushed a commit to arlosi/monaco-editor that referenced this issue Oct 29, 2021
alexdima added a commit that referenced this issue Nov 5, 2021
…slist-4.16.6

Bump browserslist from 4.16.3 to 4.16.6
alexdima pushed a commit that referenced this issue Nov 5, 2021
@qsc-jhndnn
Copy link

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 - suren-atoyan/monaco-react#68 (comment) ( I'm not using monaco-react but thought it might work ). And ideas on what else to try?

@LinYUAN-code
Copy link

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!

@yuval-illumex
Copy link

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;
}

@cbn-falias
Copy link

cbn-falias commented Jan 30, 2023

After a lot of testing and playing around this was the ultimate answer, which I was looking for: #2605 (comment)

  • 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>
  );
}

@hediet
Copy link
Member

hediet commented Feb 24, 2023

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 hediet closed this as not planned Won't fix, can't repro, duplicate, stale Feb 24, 2023
@cbn-falias
Copy link

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.

@hediet
Copy link
Member

hediet commented Mar 7, 2023

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

@github-actions github-actions bot locked and limited conversation to collaborators Apr 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feature-request Request for new features or functionality integration integration-react
Projects
None yet
Development

No branches or pull requests