Reactive Monaco editor
Hi all! Today i’m tell you a scary story –“How to install Monaco editor into you React app”
First of all — Monaco uses AMD loader with custom namespace binding, but I’m using Webpack with babel-loader. Painful problem, and I’ll show how I’ve solved it.
Step One
Install CopyWebpackPlugin
npm install --save-dev copy-webpack-plugin
Step Two
Create a webpack plugin config, that will create copy of the editor source files in your build folder.
plugins: [
new CopyWebpackPlugin([
{
from: 'node_modules/monaco-editor/min/vs',
to: 'show/vs',
}
]),
],
Step Three
Add a new container for monaco editor inside component’s render function
<div id="monaco_container"></div>
Step Four
Add Monaco’s AMD loader script into static html or load it dynamically. I’ll stick with a static html version
<script src="/show/vs/loader.js"></script>
Step Five
Add Monaco’s init and destroy functions into target component
initMonaco(){
window.require(['vs/editor/editor.main'], () => {
if(typeof monaco != "undefined") {
this.editor = monaco.editor.create(document.getElementById('monaco_container'), {
value: this.state.current_scenario_script,
language: 'javascript'
});
this.editor.onDidChangeModelContent((e)=> {
this.setState({page_edited: true, current_scenario_script: event.target.value})
});
}
});
}
destroyMonaco(){
if(typeof this.editor!="undefined")
this.editor.destroy();
}
Step Six
Insert Monaco functions calls into the component lifecycle handlers
componentDidMount() {
...
this.initMonaco();
}
componentWillUnmount(){
...
this.destroyMonaco();
}
Step Seven
Enjoy your day!