suren-atoyan / monaco-loader

The utility to easy setup monaco-editor into your browser
MIT License
177 stars 37 forks source link

[Requirement] Expectation to add an asynchronous method getMonaco to improve initial screen loading efficiency. #45

Closed LimMem closed 5 months ago

LimMem commented 5 months ago

Background

The usage of the monaco-editor package in the project is relatively low, but its package files are quite large, affecting the efficiency of the initial screen loading. If using the minified version of the monaco-editor, it will cause the window to mount the define method, impacting the loading of other UMD files in the project.

Approach

It is expected to add a getMonaco method in @monaco-editor/loader to asynchronously obtain monaco.

Code

 // 使用loader
loader.config({
  getMonaco: () => import/* webpackChunkName: 'monaco-editor' */('monaco-editor'),
});
// 路径 src/loader/index.js

/**
 * handles the initialization of the monaco-editor
 * @return {Promise} - returns an instance of monaco (with a cancelable promise)
 */
function init() {
  const state = getState(({ monaco, isInitialized, resolve, getMonaco }) => ({ monaco, isInitialized, resolve, getMonaco }));

    if (!state.isInitialized) {
      setState({ isInitialized: true });

      if (state.monaco) {
        state.resolve(state.monaco);
        return makeCancelable(wrapperPromise);
      }
      // add getMonaco code
      if (typeof state.getMonaco === 'function') {
        const monaco = state.getMonaco().then(monaco => { 
          state.resolve(monaco);
          return monaco;
        })
        return makeCancelable(monaco);
      }

      if (window.monaco && window.monaco.editor) {
        storeMonacoInstance(window.monaco);
        state.resolve(window.monaco);
        return makeCancelable(wrapperPromise);
      }

      compose(
        injectScripts,
        getMonacoLoaderScript,
      )(configureLoader);
    }

    return makeCancelable(wrapperPromise);
}
suren-atoyan commented 5 months ago

@LimMem you can do the same thing like this: (check more info here)

import('monaco-editor').then(({ default: monaco }) => {
  loader.config({ monaco });
});