Skip to content

Instantly share code, notes, and snippets.

@RoboPhred
Created April 6, 2018 23:54
Show Gist options
  • Save RoboPhred/f767bea5cbc972e04155a625dc11da11 to your computer and use it in GitHub Desktop.
Save RoboPhred/f767bea5cbc972e04155a625dc11da11 to your computer and use it in GitHub Desktop.
Monaco playground snippet for TSX support
// The Monaco Editor can be easily created, given an
// empty container and an options literal.
// Two members of the literal are "value" and "language".
// The editor takes the full size of its container.
// Important Bit #1: Typescript must see the 'file' it is editing as having
// a .tsx extension
const modelUri = monaco.Uri.file("foo.tsx")
// Important Bit #2
// By default, monaco use the "value" property to create its own model without
// any extensions, so typescript assumes ".ts"
// We need to create a custom model using the desired file name (uri).
// See the last arg.
const codeModel = monaco.editor.createModel(
`
class Foo {
private value = 42;
render() {
return <div>
<div>
Hello World
</div>
<div>The value is {this.value}</div>
</div>
}
}
`,
"typescript",
modelUri // Pass the file name to the model here.
);
// Important Bit #3: Tell typescript to use 'react' for jsx files.
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
jsx: "react"
});
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: false,
noSyntaxValidation: false
})
const editor = monaco.editor.create(document.getElementById("container"));
// Important Bit #2.5: Tell typescript to use our model.
editor.setModel(codeModel);
// Remaining Important Bits:
// Typescript will not have the typings for react. Add them using
// monaco.languages.typescript.typescriptDefaults.addExtraLib.
// Or you can do it the hard but robust way a full module system compiler options,
// and pushing up the react "d.ts" files as models. typescript-in-monaco will resolve
// imports as if all of your models with file URIs are files, even
// if you have not told monaco about the URI or it is not the one you are editing.
// (If you it this way, you will need to call
// monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true) )
// Making it use modules will help if you have a multi-file project, and need it
// to recognize and validate your other components.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment