• Stars
    star
    169
  • Rank 223,899 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatically load declaration files while typing in monaco editor instances

monaco-editor-auto-typings

Main

View the demo at lukasbach.github.io/monaco-editor-auto-typings

monaco-editor-auto-typings is a plugin for Microsoft's Monaco Editor, which automatically loads type declarations when you enter import-calls in the code editor.

Try it out in the demo! Add some imports to some libraries available on npm, such as import express from 'express';, and see that any imported variables are automatically strictly typed.

monaco-editor-auto-typings comes with lots of customization options, but is still a one-liner to add to your project. It works by loading declarations from UnPkg. They can then be optionally cached in localStorage or elsewhere.

Example image

Example

Install via yarn add monaco-editor-auto-typings monaco-editor or npm install monaco-editor-auto-typings monaco-editor --save.

import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { AutoTypings, LocalStorageCache } from 'monaco-editor-auto-typings';

const val = `
import React from 'react';
React.useEffect(0); // Type Error!
`;

// Create monaco editor instance
const editor = monaco.editor.create(document.getElementById('root')!, {
  model: monaco.editor.createModel(val, 'typescript'),
});

// Initialize auto typing on monaco editor. Imports will now automatically be typed!
const autoTypings = await AutoTypings.create(editor, {
  sourceCache: new LocalStorageCache(), // Cache loaded sources in localStorage. May be omitted
  // Other options...
});

Custom Monaco Version

By default, monaco-editor-auto-typings directly imports the monaco editor library itself. You can customize the monaco object with the monaco option. If you want to skip the entire import of monaco when bringing your own instance of monaco, you can import from monaco-editor-auto-typings/custom-editor instead of monaco-editor-auto-typings.

Known Limitations

  • Currently, scoped packages (@org/...) are not supported. This feature is blocked by this issue. @types/... packages are not affected and work fine.

Configuration

https://lukasbach.github.io/monaco-editor-auto-typings/docs/interfaces/Options.html

export interface Options {
  /**
   * Share source cache between multiple editor instances by storing
   * the cache in a static property.
   *
   * Defaults to false.
   */
  shareCache: boolean;

  /**
   * Only use packages specified in the `versions` property.
   *
   * Defaults to false.
   */
  onlySpecifiedPackages: boolean;

  /**
   * Load typings from prespecified versions when initializing. Versions
   * need to be specified in the ``versions`` option.
   *
   * Defaults to false.
   */
  preloadPackages: boolean;

  /**
   * Updates compiler options to defaults suitable for auto-loaded
   * declarations, specifically by setting ``moduleResolution`` to
   * ``NodeJs`` and ``allowSyntheticDefaultImports`` to true.
   * Other options are not changed. Set this property to true to
   * disable this behaviour.
   *
   * Defaults to false.
   */
  dontAdaptEditorOptions: boolean;

  /**
   * After typings were resolved and injected into monaco, auto-typings
   * updates the value of the current model to trigger a refresh in
   * monaco's typing logic, so that it uses the injected typings.
   */
  dontRefreshModelValueAfterResolvement: boolean;

  /**
   * Prespecified package versions. If a package is loaded whose
   * name is specified in this object, it will load with the exact
   * version specified in the object.
   *
   * Setting the option ``onlySpecifiedPackages`` to true makes this
   * property act as a whitelist for packages.
   *
   * Setting the option ``preloadPackages`` makes the packages specified
   * in this property load directly after initializing the auto-loader.
   */
  versions?: { [packageName: string]: string };

  /**
   * If a new package was loaded, its name and version is added to the
   * version object, and this method is called with the updated object.
   * @param versions updated versions object.
   */
  onUpdateVersions?: (versions: { [packageName: string]: string }) => void;

  /**
   * Supply a cache where declaration files and package.json files are
   * cached to. Supply an instance of {@link LocalStorageCache} to cache
   * files to localStorage.
   */
  sourceCache: SourceCache;

  /**
   * Supply a custom resolver logic for declaration and package.json files.
   * Defaults to {@link UnpkgSourceResolver}. Not recommended to change.
   */
  sourceResolver: SourceResolver;

  /**
   * The root directory where your edited files are. Must end with
   * a slash. The default is suitable unless you change the default
   * URI of files loaded in the editor.
   *
   * Defaults to "inmemory://model/"
   */
  fileRootPath: string;

  /**
   * Debounces code reanalyzing after user has changed the editor contents
   * by the specified amount. Set to zero to disable. Value provided in
   * milliseconds.
   *
   * Defaults to 4000, i.e. 4 seconds.
   */
  debounceDuration: number;

  /**
   * Maximum recursion depth for recursing packages. Determines how many
   * nested package declarations are loaded. For example, if ``packageRecursionDepth``
   * has the value 2, the code in the monaco editor references packages ``A1``, ``A2``
   * and ``A3``, package ``A1`` references package ``B1`` and ``B1`` references ``C1``,
   * then packages ``A1``, ``A2``, ``A3`` and ``B1`` are loaded. Set to zero to
   * disable.
   *
   * Defaults to 3.
   */
  packageRecursionDepth: number;

  /**
   * Maximum recursion depth for recursing files. Determines how many
   * nested file declarations are loaded. The same as ``packageRecursionDepth``,
   * but for individual files. Set to zero to disable.
   *
   * Defaults to 10.
   */
  fileRecursionDepth: number;

  /**
   * Called after progress updates like loaded declarations or events.
   * @param update detailed event object containing update infos.
   * @param textual a textual representation of the update for debugging.
   */
  onUpdate?: (update: ProgressUpdate, textual: string) => void;

  /**
   * Called if errors occur.
   * @param error a textual representation of the error.
   */
  onError?: (error: string) => void;
}

More Repositories

1

react-complex-tree

Unopinionated Accessible Tree Component with Multi-Select and Drag-And-Drop
TypeScript
925
star
2

yana

Powerful note-taking app with nested documents, full-text search, rich-text editor, code snippet editor and more
TypeScript
253
star
3

obsidian-code-files

Plugin for ObsidianMD to show and edit code files along other notes.
TypeScript
103
star
4

obsidian-file-order

Obsidian plugin to reorder files with drag-and-drop by customizing a number-prefix in the filenames
TypeScript
63
star
5

intellij-ts-react-livetemplates

Live Templates for Typescript and React
TypeScript
48
star
6

headless-tree

Spiritual Successor to react-complex-tree. Work In Progress.
TypeScript
36
star
7

ink-form

Complex user-friendly form component for React Ink
TypeScript
31
star
8

chakra-ui-contextmenu

Context Menu component for Chakra UI
TypeScript
23
star
9

devsession

Open-Source collaborative IDE with many features and extremely quick setup
TypeScript
22
star
10

pensieve

Desktop app for recording meetings from locally running apps and transcribing and summarizing them with a local LLM
TypeScript
16
star
11

github-takeout

A utility for cloning all your repos, including issues, discussions, stargazers and more!
TypeScript
12
star
12

reportal

A dashboarding- and item management tool for Github.
TypeScript
9
star
13

synergies

Create a performant distributed context state for React by composing reusable state logic.
TypeScript
9
star
14

gfont-cloudless

repo template for self-hosting google fonts without relying on google host servers
JavaScript
8
star
15

pauspapier

A utility tool for overlaying a transparent screenshot crop on top of your screen
TypeScript
7
star
16

obsidian-proper-dark

Theme for ObsidianMD with darker backgrounds and more colorful features.
CSS
6
star
17

vileo

Simple screen & webcam recording tool that works right from the browser
TypeScript
6
star
18

react-accessible-menu

Accessible keyboard-friendly interactive list/menu component
TypeScript
6
star
19

mockingbirb

Desktop app for configuring HTTP mocking servers
TypeScript
4
star
20

tersus

A simple dashboarding tool to keep track of everyday tasks
TypeScript
3
star
21

retypetron

Minimalistic React + TypeScript + Electron Boilerplate. Nothing more.
TypeScript
3
star
22

github-bulk-unsubscriber

Unwatch large quantities of Github repositories in an instance. Specify the repos to unwatch with a Regex.
JavaScript
3
star
23

pdfjoin

Quickly join PDF files from the command line
TypeScript
2
star
24

ts-starter

Typescript starter repo with eslint setup
JavaScript
2
star
25

redirectgen

CLI tool for generating static URL shortener HTML documents from a yaml data source
JavaScript
2
star
26

json-extract-path

CLI tool to extract a variable from a JSON file based on a JSONPath value
JavaScript
2
star
27

slyder

Webbased free-to-play puzzle-game.
TypeScript
2
star
28

edu-recaps

Recaps for university courses
HTML
2
star
29

blackmaker

WIP React UI Framework
TypeScript
2
star
30

orion

Free web-based board/puzzle game
TypeScript
2
star
31

publish-fast

A straight forward tool for streamlining the publishing of NPM packages without a lot of setup and work
TypeScript
2
star
32

embeddable-monaco

Monaco Editor instance running in an embeddable iframe with an easy-to-use messaging and parameter API
TypeScript
1
star
33

scripts

Various scripts for doing stuff fast
TypeScript
1
star
34

personalpage2020

Personal website source code.
SCSS
1
star
35

ts-regex

A regex matcher implementation completely written in TypeScripts Type System.
TypeScript
1
star
36

allias

Easily manage local commandline aliases
TypeScript
1
star
37

tauri-windows-kill-repro

Repro of issue with tauri where killing spawned children does not work under windows
CSS
1
star
38

styling-evalutation

JavaScript
1
star
39

lukasbach

Github profile repo
1
star
40

noindent

Remove indentation from multiline strings, e.g. ones that were created with template literals
TypeScript
1
star
41

hexagonopolis

Webbased free-to-play puzzle-game.
TypeScript
1
star
42

scaffold-cli

Templating tool for building reusable and configurable code templates in a central place.
TypeScript
1
star
43

ires

A commandline tool for duplicating and resizing image files.
JavaScript
1
star
44

piek

Peek into files from the command line
TypeScript
1
star
45

toolbelt

PDF Merger, Color picker, Text Diff tool and Office media extractor in one webapp
TypeScript
1
star
46

yana-homepage

Homepage source code for yana
TypeScript
1
star
47

textannotation

Eclipse plugin for annotating text files.
Java
1
star
48

fonts

font bundles used in various projects
JavaScript
1
star
49

npmdocs

A comprehensive typedoc documentation of all packages on npm
TypeScript
1
star
50

cli-ts-commander-starter

Template repo for a Typescript-based CLI tool with commander
JavaScript
1
star
51

swquote

Search for any Star Wars quote line, and fine the corresponding video snippet. https://swquote.herokuapp.com
CSS
1
star
52

movie-color-strip

Generate linear color compositions from movies
TypeScript
1
star
53

lukasbachcom2023

Personal website source code.
TypeScript
1
star
54

test-repo

1
star
55

gh-repo-api-playground

Playyground for testing Github's Git Rest Api
1
star
56

.github

community health defaults
1
star
57

app-notifications

Data storage for app notifications including Yana
TypeScript
1
star
58

filenode

Filenode is an file explorer based in php and javascript, that uses the server its hosted on as filesystem. It's easy to install and easy to use, requiring no database and minimal disc space.
PHP
1
star