You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// main.js// Import the ESM version of Monaco Editorimport*asmonacofrom'monaco-editor';// Set up Monaco Editorconsteditor=monaco.editor.create(document.getElementById('editor'),{value: `// Write your JS code here...\n`,language: 'javascript',theme: 'vs-dark',});constexecuteButton=document.getElementById('execute');constoutputTextArea=document.getElementById('output');// Function to redirect console methodsconstredirectConsoleOutput=()=>{constoriginalLog=console.log;constoriginalInfo=console.info;constoriginalWarn=console.warn;constoriginalError=console.error;// Custom handler to redirect output to the textareaconstlogToOutput=(method,args)=>{originalLog.apply(console,args);// Also call the original method to keep logging to consoleoutputTextArea.value+=`[${method.toUpperCase()}] ${args.join(' ')}\n`;};// Override console methodsconsole.log=(...args)=>logToOutput('log',args);console.info=(...args)=>logToOutput('info',args);console.warn=(...args)=>logToOutput('warn',args);console.error=(...args)=>logToOutput('error',args);};// Set up the Execute button click handlerexecuteButton.addEventListener('click',async()=>{constcode=editor.getValue();outputTextArea.value='';// Clear output// Redirect console outputredirectConsoleOutput();try{// Remove any previous <script> tags that were added dynamicallyconstoldScript=document.getElementById('dynamicScript');if(oldScript){oldScript.remove();}// Create a new <script> tag to execute the user codeconstscript=document.createElement('script');script.id='dynamicScript';script.type='module';// Ensure the module scope if neededscript.innerHTML=` import { fetch } from '@tauri-apps/plugin-http'; import { invoke } from '@tauri-apps/api'; async function executeUserCode() { try {${code} // Execute the user's code here } catch (error) { console.error('Error executing user code:', error); } } executeUserCode(); `;// Append the <script> to the bodydocument.body.appendChild(script);}catch(error){outputTextArea.value=`Error: ${error.message}`;}});
I tried to use Service Worker to intercept the request, but some code like import './inlineProgressWidget.css'; in js still could not be handled via the browser esm loader without bundler.
How about build monaco-editor both esm-bundler and esm-browser just like vue does.
The vue seems use rollup to build both esm-bundler and esm-browser output.
sw.js
self.addEventListener('install', event => {
console.log('Service worker installed');
});
self.addEventListener('activate', event => {
console.log('Service worker activated');
});
self.addEventListener('fetch', event => {
event.respondWith(handleRequest(event)); // Pass handleRequest directly to respondWith
});
async function handleRequest(event) {
try {
let request = event.request.clone();
const url = new URL(request.url);
// Get the extension of the last part of the pathname
const extension = url.pathname.includes('.') ? url.pathname.split('.').pop() : '';
// Check if the URL starts with `/assets` and doesn't end with `/`, `.js`, or `.css`
if (url.pathname.startsWith(`/assets`) && !url.pathname.endsWith('/') && !['js', 'css'].includes(extension)) {
console.info(`Rewrite url: ${url.href} to ${url.href}.js`);
// The request URL is immutable, so we need to create a new Request object with the modified URL
request = new Request(`${url.href}.js`, {
method: request.method,
headers: request.headers,
body: request.body, // Only use body if the method supports it (e.g., POST, PUT)
mode: request.mode,
credentials: request.credentials,
cache: request.cache,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
integrity: request.integrity,
keepalive: request.keepalive,
});
}
// Check if the response for the request is already in the cache
const cache = await caches.open('assets-cache');
let response = await cache.match(request.url);
if (!response) {
console.info(`Cache miss for ${request.url}`);
response = await fetch(request);
const responseClone = response.clone(); // Clone the response to put it into the cache
event.waitUntil(cache.put(request.url, responseClone));
}
return response; // Immediately return the response (or the cached response)
} catch (error) {
console.error(`Error in handleRequest: ${error}`);
// Return a default response if an error occurs, to avoid interruption
return new Response('Error fetching resource', { status: 500 });
}
}
Reproducible in vscode.dev or in VS Code Desktop?
Reproducible in the monaco editor playground?
Monaco Editor Playground Link
n.a.
Monaco Editor Playground Code
n.a.
Reproduction Steps
I want to use esm build of monaco editor in pure frontend html, means without bundler like webpack, vite and without server.
The following is the demo code I wrote, The following code in browser doesn't work due the import file is not end with
.js
suffix.Here is the demo code
demo code
I have tried to use https://github.com/guybedford/es-module-shims or https://github.com/systemjs/systemjs, but none of them works for me.
Actual (Problematic) Behavior
The url of import module doesn't end with .js, so the static server will not work as expected.
Expected Behavior
The import of esm build should end with .js to make it work for pure browser.
Additional Context
No response
The text was updated successfully, but these errors were encountered: