Monaco editor pre-build for standalone usage
npm install @jsx6/editor-monacoself.MonacoEnvironment so when Monaco editor wants to start the worker it can ask where specific worker JS file is. We communicate this information using a global variable (using too many global variables is bad, but there are legitimate use-cases, and this one is).
js
self.MonacoEnvironment = { getWorkerUrl: (moduleId, label)=>{
if(label === 'javascript') return 'ts.worker.js'
// .....
}}
`
Same worker bundle can handle multiple languages, so we usually will have a mapping similar to this
`js
const workerMap = {
editorWorkerService: 'editor',
css: 'css',
html: 'html',
json: 'json',
typescript: 'ts',
javascript: 'ts',
less: 'css',
scss: 'css',
handlebars: 'html',
razor: 'html',
}
`
The worker files are named by convention: editor.worker.js, ts.worker.js, html.worker.js, css.worker.js, json.worker.js so their urls can easily be generated.
workers and CDN
Although you can simply use the main editor code from CDN by adding script tag to your html:
`html
`
it is not as simple as that with web workers. Trying to run worker from CDN on your page will cause a CORS error.
There is a neat trick that I learned about while preparing to use this pre-built Monaco via CDN. The trick was part of Monaco examples at some point and I found it by googling in some old commits. They removed it later on (not sure why).
To be able to run worker code from CDN you need to generate data url with a script inside that tells Monaco where base is, and call importScripts inside the worker script. This way the worker is local (no CORS error) and then our small two-liner worker loads the external script ... and it works :).
`js
const workerBase = 'https://www.unpkg.com/@jsx6/editor-monaco@0.48.0/dist/'
self.MonacoEnvironment = { getWorkerUrl: (moduleId, label)=>{
if(label === 'javascript'){
const proxyCode = self.MonacoEnvironment = { baseUrl: '${workerBase}'};
return data:text/javascript;charset=utf-8,${encodeURIComponent(proxyCode)}
}
// .....
}}
`
To streamline this and avoid too much copy/pasta setPreBuiltWorkerBase script is built-in and added to Monaco export.
Local copy of Monaco pre-built files more details
`html
`
Monaco pre-built files from CDN more details
`html
``