webpack 如何修复错误:在vue-cli-3中加载monaco编辑器的外部模块时出现意外用法

k2fxgqgv  于 2023-01-26  发布在  Webpack
关注(0)|答案(2)|浏览(821)

当我尝试在我的vue-cli-3项目中包含优化选项时,在一些页面中使用monaco-editor,我在控制台中得到以下错误:

languageFeatures.js?ff36:85 Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js?ccf6:540)
    at eval (webWorker.js?af50:54)

下面是我的vue.config.js文件:

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const PurgecssPlugin = require("purgecss-webpack-plugin");

module.exports = {
    transpileDependencies: ["vuex-persist", "vuex-persistedstate"],
    configureWebpack: {
        devtool: false,
        optimization: {
            splitChunks: {
                minSize: 10000, 
                maxSize: 250000, 
            },
            nodeEnv: "production",
            minimize: true,
            minimizer: [
                new TerserPlugin({
                    extractComments: 'false',
                    parallel: true,
                }),
            ],
            removeEmptyChunks: true,
            removeAvailableModules: true,
            mergeDuplicateChunks: true
        },
        plugins: [
            new MonacoWebpackPlugin({
                languages: ['javascript', 'css', 'html', 'typescript', 'json'],
                features: ['!gotoSymbol'],
            }),
            new PurgecssPlugin({paths: glob.sync(`${PATHS.src}/**/*`, {nodir: true})}),
        ],
    }
};
  • 摩纳哥编辑器- v0.20.0
  • 摩纳哥编辑器webpack插件- v1.9.0
  • Vue/客户端- v4.3.1

所以问题是,我怎样才能避免这个错误呢?

vjhs03f7

vjhs03f71#

在尝试导入editor.main.js之前,应定义Monaco环境的基URL并导入主工作进程。您可以尝试通过在尝试加载编辑器之前执行以下代码来解决问题。

(window as any).MonacoEnvironment = {
      getWorkerUrl: function (workerId, label) {
          return `data:text/javascript;charset=utf-8,${encodeURIComponent(`
              self.MonacoEnvironment = { baseUrl: '${window.location.origin}/' };
              importScripts('${window.location.origin}/vs/base/worker/workerMain.js');
          `)}`;
      }
};

还需要注意的是,应将URL更改为承载vs文件的位置。

xienkqul

xienkqul2#

您还可以通过以下方式加载Web工作程序(如有必要,请更正monaco workers的路径):

window.MonacoEnvironment = {
  getWorker: (workerId, label) => {
    if (label === 'json') {
      return new Worker(new URL('monaco-editor/esm/vs/language/json/json.worker?worker', import.meta.url));
    }
    return new Worker(new URL('monaco-editor/esm/vs/editor/editor.worker?worker', import.meta.url));
  }
};

相关问题