vdesjs / vite-plugin-monaco-editor

A vite plugin for the Monaco Editor
MIT License
206 stars 36 forks source link

error loading workers when specifying basePath in vite.config.js #44

Open justinrlle opened 1 year ago

justinrlle commented 1 year ago

First, let me thank you for your plugin and the work you've put, it really helped us!

I've witnessed an error while using a basePath in my vite.config.js.

I have a feeling it's linked to #19 and maybe other issues.

I've reproduced the error in the smallest config possible in this repository: vite-monaco-basepath-error. It also contains the fix to the configuration to correct this behavior.

Quick summary

When specifying a base path in the config for vite, this plugin will use this basepath to calculate the dist directory for the workers. This produce a double nesting of the base path, rendering the workers impossible to load

Is there a workaround?

Yes, you just need to override the distPath by specifying customDistPath in the plugin config. You can see an exemple further down in the issue.

Explanation with images

Here is the vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import monacoEditorPlugin from 'vite-plugin-monaco-editor';

// https://vitejs.dev/config/
export default defineConfig({
  base: '/nested',
  plugins: [
    vue(),
    monacoEditorPlugin.default({}),
  ],
});

And when I do a yarn build, the monaco workers are put in dist/nested/monacoeditorwork, while the other assets are simply put in dist/assets without the nested part, meaning that trying to load the workers will fail:

Screenshot 2023-02-15 at 12 03 53

And as you can see, if I try to directly go to /nested/nested/monacoeditorwork/json.worker.bundle.js, it will correctly show the file content:

Screenshot 2023-02-15 at 11 43 10

I can fix this by customizing the dist path:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import monacoEditorPlugin from 'vite-plugin-monaco-editor';
import path from 'node:path';

// https://vitejs.dev/config/
export default defineConfig({
  base: '/nested',
  plugins: [
    vue(),
    monacoEditorPlugin.default({
      customDistPath(root, buildOutDir) {
        return path.join(root, buildOutDir, 'monacoeditorwork');
      }
    }),
  ],
});

And it will work again.

Screenshot 2023-02-15 at 12 04 48

What is the underlying problem?

My understanding is that the default distPath should not include the basepath, as the other assets in the vite pipeline are doing, but I'm not exactly sure.

At least, this workaround works for me and should for others!

favorite58 commented 1 year ago

我也遇到改问题了,目前项目是子应用,vite构建工具,配置base后打包资源路径错误