react-ace: Could not load worker

Problem

Couldn’t load worker, JSON syntax validation doesn’t work. I see Could not load worker warning in the browser console.

Also, I tried to import the json worker

import "ace-builds/src-noconflict/worker-json";

and got the error

TypeError: Cannot read property 'window' of undefined

Sample code to reproduce the issue

import React from "react";
import ReactDOM from "react-dom";
import AceEditor from "react-ace";

import "ace-builds/src-noconflict/ace";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-github";

let text =
  '{\n  "id": 0,\n  ' +
  '"script": """\n   function add(x, y) {\n      return x + y;\n   }\n   add(1, 2);\n   """' +
  ',\n   "descr": "add two numbers"\n}';

function App() {
  return (
    <div className="App">
      <h1>Code Editor Demo</h1>
      <AceEditor
        mode="json"
        theme="github"
        onChange={(value, stat) => {
          console.log("onChange", value, stat);
        }}
        value={text}
        name="UNIQUE_ID_OF_DIV"
        editorProps={{ $blockScrolling: true }}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

References

Codesandbox https://codesandbox.io/embed/ace-worker-3-vrr68

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 8
  • Comments: 34 (1 by maintainers)

Commits related to this issue

Most upvoted comments

You need to either include the webpack-resolver

import "ace-builds/webpack-resolver";

or configure the url for each mode separately

import jsonWorkerUrl from "file-loader!ace-builds/src-noconflict/worker-json";
ace.config.setModuleUrl("ace/mode/json_worker", jsonWorkerUrl)
import cssWorkerUrl from "file-loader!ace-builds/src-noconflict/worker-css";
ace.config.setModuleUrl("ace/mode/css_worker", cssWorkerUrl)

both methods require “file-loader”

also react-ace tries to load brace if ace is not already imported so ace-builds needs to be imported before react-ace.

import "ace-builds";
import AceEditor from "react-ace";

setOptions={{ useWorker: false }}

works for me. Thanks @khoomeister

Did anyone get this working with create-react-app? Mine gets stuck compiling forever if I add:

import 'ace-builds/webpack-resolver';

I added the last 3 lines to add javascript-worker :

import AceEditor from "react-ace";
import "ace-builds/src-min-noconflict/mode-javascript";
import "ace-builds/src-min-noconflict/theme-tomorrow_night_eighties";
import "ace-builds/src-min-noconflict/ext-language_tools";
import "ace-builds/src-min-noconflict/ext-spellcheck";
import "ace-builds/src-min-noconflict/snippets/javascript";
import 'ace-builds/src-min-noconflict/ext-searchbox';
const ace = require('ace-builds/src-noconflict/ace');
ace.config.set("basePath", "https://cdn.jsdelivr.net/npm/ace-builds@1.4.3/src-noconflict/");
ace.config.setModuleUrl('ace/mode/javascript_worker', "https://cdn.jsdelivr.net/npm/ace-builds@1.4.3/src-noconflict/worker-javascript.js");

You can copy/paste the file worker-javascript.js in your local environment if you don’t want to be dependant of cdn.jsdelivr.net.

For those of you using Vite, I was able to get it working using Explicit URL Imports (appending ?url to the end of the worker import):

import ace from 'ace-builds/src-noconflict/ace';
import jsonWorkerUrl from 'ace-builds/src-noconflict/worker-json?url';

ace.config.setModuleUrl('ace/mode/json_worker', jsonWorkerUrl);

// ... mode and theme imports here

I fixed by adding useWorker: false to setOptions if importing modules directly. If this is a good solution, README.md basic usage should be updated unless I’m missing something.

I leave the full NextJS@9.3 integration here.

import dynamic from "next/dynamic";

const AceEditor = dynamic(
  async () => {
    const reactAce = await import("react-ace");

    // prevent warning in console about misspelled props name.
    await import("ace-builds/src-min-noconflict/ext-language_tools");

    // import your theme/mode here. <AceEditor mode="javascript" theme="solarized_dark" />
    await import("ace-builds/src-min-noconflict/mode-javascript");
    await import("ace-builds/src-min-noconflict/theme-solarized_dark");

    // as @Holgrabus commented you can paste these file into your /public folder.
    // You will have to set basePath and setModuleUrl accordingly.
    let ace = require("ace-builds/src-min-noconflict/ace");
    ace.config.set(
      "basePath",
      "https://cdn.jsdelivr.net/npm/ace-builds@1.4.8/src-noconflict/"
    );
    ace.config.setModuleUrl(
      "ace/mode/javascript_worker",
      "https://cdn.jsdelivr.net/npm/ace-builds@1.4.8/src-noconflict/worker-javascript.js"
    );

    return reactAce;
  },
  {
    ssr: false // react-ace doesn't support server side rendering as it uses the window object.
  }
);

export default () =>  <AceEditor mode="javascript" theme="solarized_dark" />

I’m experiencing something similar for CSS, getting the following error in browser console:

Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/settings/landing-page/worker-css.js' failed to load.

When attempting to import worker directly

import 'ace-builds/src-noconflict/worker-css';

My build failed with:

ERROR in ../node_modules/ace-builds/src-noconflict/worker-css.js
Module not found: Error: Can't resolve 'ace/lib/es5-shim' in 'path/to/node_modules/ace-builds/src-noconflict'

If you want to use the workarounds in Typescript you’ll need to do this to set ace config:

import { config } from 'ace-builds';

config.set(
  "basePath",
  "https://cdn.jsdelivr.net/npm/ace-builds@1.4.8/src-noconflict/"
);
config.setModuleUrl(
   "ace/mode/javascript_worker",
   "https://cdn.jsdelivr.net/npm/ace-builds@1.4.8/src-noconflict/worker-javascript.js"
);

Adding webpack-resolver to my create-react-app project leads to a huge increase in compile time, and adds hundreds of files to the build directory - I assume one for each module in ace-builds that it configures. Configuring the url for just the modules that I need works fine, though.

This seems like it’s an issue with either react-scripts or ace-builds, not react-ace.

@nightwing that works but importing ace-builds before react-ace fails in Firefox for me. I got it to work with:

import AceEditor from 'react-ace';
import 'ace-builds/webpack-resolver';
// then the mode, theme & extension
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-tomorrow_night';
import 'ace-builds/src-noconflict/ext-searchbox';

But I couldn’t get it to work with my tests. The webpack-resolver import line fails in tests with

TypeError: Cannot read property 'setModuleUrl' of undefined

I’m guessing I need mock ace with something like

global.ace = require('ace-builds/src-min-noconflict/ace');

@Cactusx09 thank you!!!

For those who don’t know how to add webpack configs to a nextjs project, here’s my snippet: next.config.js:

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  ...
  webpack: (config, options) => {
    config.module.rules.push({
      test: /ace-builds.*\/worker-.*$/,
      type: 'asset/resource',
    });
    return config;
  },
};

module.exports = nextConfig;

The following seems to have worked for me. The key is the order of imports and the last three lines (including the comment!) I got it from this reply.

import 'ace-builds'
import AceEditor from 'react-ace';
import ace from 'ace-builds/src-noconflict/ace'
// import mode-<language> , this imports the style and colors for the selected language.
import 'ace-builds/src-noconflict/mode-xml';
// there are many themes to import, I liked monokai.
import 'ace-builds/src-noconflict/theme-github';
// this is an optional import just improved the interaction.
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-beautify';
// eslint-disable-next-line import/no-webpack-loader-syntax
import xmlWorkerUrl from "!!file-loader!ace-builds/src-noconflict/worker-xml";
ace.config.setModuleUrl("ace/mode/xml_worker", xmlWorkerUrl);

For those searching how to implement workers now, when file-upload is deprecated with Webpack 5 asset/resource.

webpack config:

rules: [
  {
      test: /ace-builds.*\/worker-.*$/,
      type: "asset/resource"
  },
],

component:

import AceEditor from "react-ace";
import { config } from "ace-builds";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-github";
import "ace-builds/src-noconflict/ext-language_tools";

import jsWorkerUrl from "ace-builds/src-noconflict/worker-javascript";
config.setModuleUrl("ace/mode/javascript_worker", jsWorkerUrl);

To fix the typescript “no module declaration” error, just add the global.d.ts file to your src folder:

declare module "ace-builds/src-noconflict/worker-javascript";

I added the following test to Webpack

  module: {
    rules: [
      {
        test: /ace-builds.*\/worker-.*$/,
        loader: 'file-loader',
        options: {
          esModule: false,
          name: '[name].[hash:8].[ext]',
        },
      },
    ],
  },

then I was able to import as following

import ace from 'ace-builds/src-noconflict/ace';
import cssWorkerUrl from 'ace-builds/src-noconflict/worker-css';

ace.config.setModuleUrl('ace/mode/css_worker', cssWorkerUrl);

I’m using a create-react-app project.

The only thing I needed to do was to add this in my App.tsx:

import 'ace-builds/webpack-resolver'

Setting useWorker to false disables syntax checking at least, maybe other things, so I didn’t want to use that.

I don’t know yet if this is good enough to make it work with tests as per arjunu’s comment above.

@jan-osch so if I want to use my “customWorker.js” for example, i’ve to set ace.config.setModuleUrl("ace/mode/myWorker", "/customWorker.js") ? (putting customWorker.js in the /public folder)

if you use vite, you can …

import { viteStaticCopy } from 'vite-plugin-static-copy'

export default defineConfig(() => {
    plugins: [
      viteStaticCopy({
        targets: [
          {
            src: [
              'node_modules/ace-builds/src-min-noconflict/ace.js',
              'node_modules/ace-builds/src-min-noconflict/mode-json.js',
              'node_modules/ace-builds/src-min-noconflict/worker-json.js'
            ],
            dest: 'node_modules/ace-builds/src-min-noconflict/'
          }
        ]
      })],
    })