How to use addExtraLib in Monaco to add lodash library
Asked Answered
D

1

6

I want the Monaco editor to recognized lodash as a library. To fix this I'm using addExtraLib(content: string, filePath?: string). As lodash is my node module I can provide a file path but what to write in the content. I need the entire functions of lodash to be enabled in my monaco-editor.

I'm able to add a small custom library using https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-javascript-defaults

Need help to resolve this issue. enter image description here

Doggo answered 27/4, 2021 at 13:37 Comment(0)
U
-1

You can manage it with Webpack.

  1. With CopyPlugin copy interesting d.ts files that you want to use within Monaco Editor to your project's output.
  2. With ManifestPlugin create manifest file with the list of the d.ts files that you want to load to Monaco
plugins: [
    new CopyPlugin({
      patterns: typesToUse,
    }),
    new ManifestPlugin.WebpackManifestPlugin({
      fileName: 'dts-files.json',
      generate: (seed, files) => {
        return files.filter(file => file.name.endsWith('.d.ts')).map(file => file.name);
      }
    })
    ]
  1. Use created by Webpack sources to fill Monaco definitions:
async function loadDtsFiles() {
  const dtsFiles = await (await fetch("./dts-files.json")).json();
  return Promise.all(
    dtsFiles.map(async filePath => {
      const content = await (await fetch(`./${filePath}`)).text();
      return {
        filePath, content,
      }
    })
  ); 
}

async function setExtraLibs() {
  const extraLibs = await loadDtsFiles();
  monaco.languages.typescript.typescriptDefaults.setExtraLibs(
    extraLibs.map(extraLib => ({
      ...extraLib,
      filePath:   monaco.Uri.file(`./${extraLib.filePath}`)
    }))
  );
}

function createMonacoInstance() {
  let model = monaco.editor.createModel(`import * as _ from "./lodash";

  const students = [
    { id: 1, name: 'John', grade: 'A' },
    { id: 2, name: 'Alice', grade: 'B' },
    { id: 3, name: 'Bob', grade: 'A' },
    { id: 4, name: 'Jane', grade: 'C' }
  ];
  
  const studentsByGrade = _.groupBy(students, "grade");`, "typescript", monaco.Uri.file("./index.ts"));
  monaco.editor.create(document.body, { model });
}

  
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
  moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
});
createMonacoInstance();
setExtraLibs();

Repo | Demo

Unwind answered 24/2 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.