Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete

Rate this content
Bookmark
The video covers how to build a custom JavaScript editor using CodeMirror, focusing on features like custom themes, syntax highlighting with the lezer parser, and linting. It demonstrates how to change the color of JavaScript comments to match organizational preferences and save the editor's history in local storage for undo/redo functionality. The talk explains how to add a custom linter using extensions and manage error strictness with LintGutter. It also delves into implementing autocomplete, including js doc completion and global object autocompletion, and highlights the importance of maintaining the original autocomplete functionality. Finally, the video discusses the use of ReactCodeMirror for easier integration with React projects, the challenges of navigating extensive documentation, and the benefits of TypeScript for safer production code.

From Author:

Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?


In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.

This workshop has been presented at React Day Berlin 2022, check out the latest edition of this React Conference.

FAQ

The presenter of the course is Hussain, a staff developer at Shopify who mainly focuses on the front end and has been using React for seven years.

The main focus of the course is on installing and using React and CodeMirror to create a custom code editor within a web application.

Shopify chose to use CodeMirror because it is a powerful library that allows the creation of custom code editors out of the box, supports multiple languages, is flexible, and has extensive documentation.

Key features of CodeMirror include the ability to create custom themes, add linting to catch errors, implement basic and complex auto-complete, and support for multiple languages.

The advantages of using StackBlitz include not needing to install libraries directly and faster performance compared to other environments like CodeSandbox, as it runs code locally in the browser using WebAssembly.

CodeMirror offers customization options such as creating custom themes, adding custom linting, and implementing customized auto-complete features.

CodeMirror can handle multiple code editors on a single screen, each responsible for its own state, and supports different languages like JavaScript, HTML, CSS, and Python.

The 'view update' feature in CodeMirror is significant because it provides access to the code editor's state and allows developers to manage the state and implement features like local storage for saving code history.

The syntax tree in CodeMirror helps parse the code into nodes, allowing developers to implement more specific and customized features such as auto-complete and linting.

The custom linter in CodeMirror works by using an external linter library (like js-hint) to process the code, identify errors, and provide a diagnostic object that CodeMirror uses to display linting errors.

Hussien Khayoon
Hussien Khayoon
Kahvi Patel
Kahvi Patel
86 min
30 Nov, 2022

Comments

Sign in or register to post your comment.

Video Transcription

1. Introduction to CodeMirror Library

Short description:

In this part, we will discuss CodeMirror, a powerful library that allows you to create your own editor. We will cover the basic setup, adding themes, linting, and auto-complete features. The library is widely used at Shopify and we had to upgrade it to meet our specific needs. Despite the thorough documentation, we had to navigate through examples to implement linting and custom auto-complete. We will be using ReactCodeMirror, a helpful library that simplifies the usage of CodeMirror. Let's dive into the coding process and follow the instructions.

This text is the first part: "Course 3. Developing in a Web browser"... I'm going to explain how to install React playoffs..." I'm Hussain, I'm a staff developer here at Shopify. I mostly focus on the front end. I've been using React for Seven years, closely. I mean, when it came out, let's talk about CodeMirror.

So what are we doing with CodeMirror? Today, the agenda is, we're going to talk about the library itself. We're going to talk about some basic setup. We're going to add our own themes and use additional themes that they have. Add our own linting. So, the ability to catch some errors. Adding a general auto-complete, something more complex of an auto-complete in JavaScript, and we're going to do more custom auto-complete.

I will be using JavaScript just because I think it's more accessible. Not everybody uses TypeScript. I wanted to just make it more general. Also, it saves a lot of time here and all the errors we might get. So, why are we talking about this? CodeMirror itself is a very, very, very powerful library. It allows you to create your own editor out of the box, and it has a lot of features and a lot of documentation. How we landed on this problem was at Shopify, we have a few places across our app that merchants use. Different across different code bases that other developers use in our docs, where we want to show a code editor, whether you can edit it or not, in different languages, adding certain syntax. Across the app, and Shopify has been around for a long time, I've only been there for a year, we noticed that CodeMirror was the main one being used. Also, it wasn't the most up-to-date version, so part of what I did was had the learn CodeMirror and add a new feature where merchants are able to add their own code, essentially, add their own code and fire off events in those codes. What that means is a merchant can say, after I make a sale, please send Facebook the message about my sale, meaning tell them that I sold something, this particular product at this particular price with these parameters. We fire off that event for you, but you put in the code that you want to fire off because you want to send it to Facebook anywhere else. So we had to have a coding environment and that's just one of the use cases that we had it at.

So I think a lot of what we do here as developers, because you can create your own, you can write your own CodeMirror, you can create your own editor and that's cooler, so to speak, but generally, we find ourselves if there's something out there that's better, maybe it's not the best thing that you should do, and we all know that and we all have to make those difficult decisions about should we use this? Should we make our own? And something like this that already existed in the code base that other teams were using, it was a good idea to use this. But the problem is it wasn't up to date. We had to upgrade it. And I think that leads me to the point about why this is so important is because I found myself, I I've been developing for about 10 years. I found the most important, the thing I'm doing the most is not writing new, cool stuff and cutting edge innovation. Generally speaking, I'm giving libraries on the front end or backend, but let's just say front end, and I have to, what I call wrangle them. I have to make them work for what I want it to do. At the end of the day, it's nice when the library just works. But rarely, is that the case because business means code and business makes code complicated. So, um, what I've had to do with CodeMirror and what our team had to do was essentially make it work for our use case. And it was an environment where you see documentation like this and you get very excited because it's, it's very thorough, but documentation, what I learned is very nice. But the problem is when it's very thorough, it doesn't mean it's very easy to find out to do what you want. So we had to do a linting. We had to do autocomplete. We had to add our own, but it wasn't very apparent from the examples, but the documentation was there. So let's get through here and let's start coding here. But I just thought that introduction would be important. So one thing to know here is we're using ReactCodeMirror. This just makes using CodeMirror a lot easier. You can make your own wrappers on what our teams do, but this library here is quite useful. It essentially just makes things into its own packages and you'll see that we have a lot of packages here and that's just the architecture they decided to do to allow you and give you more flexibility. They give some basic examples of what you can do. They support multiple languages, so it's easy to use out of the box when you're using React. So let's follow the instructions here. One thing that's cool about StackBlitz is that you don't actually need to install these libraries directly, so you should do Yarn add.".

2. Exploring CodeMirror Setup in StackBlitz

Short description:

In this part, we explore the basic setup of CodeMirror in StackBlitz. We discuss the speed and architecture of StackBlitz, highlighting its use of WebAssembly for fast execution. The basic setup of the code editor allows control over height, provides autocomplete, collapsing, and line-gutter features. We also touch on the power of extensions in CodeMirror and the challenges of navigating the extensive documentation. Additionally, we mention the ability to add TSX True and the limitations of adding divs within JavaScript.

So you'll see here, if you're following along with StackBlitz, I'm going to take this code here with the basic setup and I'm just going to paste it in here. And I'm just going to change this to app.js. If it works, if it doesn't work, we'll revert it back.

So as you can see here, it's already asking me to I have the 10-D list here, so I can't see a lot of what I'm doing. Okay. It's going to ask me to install these parameters. Pretty cool. I don't know if you noticed, but StackBlitz is actually pretty, pretty fast compared to a lot of the stuff here. And a lot of the other kind of environments, I think Code Sandbox particularly is what I used. And what's really interesting about their architecture is everything I think is written in, correct me if I'm wrong, Covey is in WebAssembly, and just loaded on your browser instead of like, you know going back to your code, sorry, going to the cloud every time you update something and asking a server for things. So as far as I know, that's what they do. And it's very, very fast if you use it. So I don't know if you notice that or if you're a user, I just found out about this pretty recently from a call.

Yeah, there's an interesting difference between how they execute code on CodeSandbox versus in StackBlitz. I don't know the details of it, but I do know that StackBlitz is local, which is awesome. Yeah, so, thanks for that, Covey. So as you can see here, we have a basic setup of a code editor. And you see, we didn't really need to do much here, but there's some important nuances. The first one here is, we can control height. Pretty easy thing here. You can make this 250 if you want. You'll see that it increased in size. You see here, we have initial kind of value. And my mouse is going crazy. And another thing that you can do here is, you can see you have some things out of the box, like autocomplete. For example, for of loop, we have it right here. We could do an if statement. It's going to do an if block out of the box. There's no linting errors or anything like that out of the box. But you can see here, with the basic setup, you can even do some collapsing, which is really nice. You have this, what's called a line-gutter or the gutter, which allows you to show the lines. And they have different colors for highlighting and everything like that. Also, let's see here. You can do a trycatch block if you want. And it's pretty nice out of the box. So what makes this possible is you have, you're plugged into these language kind of plugins or packages. And JavaScript allows you to essentially make this editor specifically for JavaScript. And you call it as a function, and it's inside the extensions. The extension is the most powerful thing in Codemirror, and what I love about it is, everything, every feature you want to add, you can do through extensions. Now, the problem with it, I found is that the documentation is extensive. But it's also confusing because a lot of times what they do is they'll use their own kind of terminology in other objects and just say like, oh, it provides this and facets. And what I found with that is like, I'm, you know, it's a bit overwhelming and you got to like dig into more to understand what's really going on. I don't know about you, but I like to follow examples. So, and that's how I was trying to do things. So a lot of it was trying to find things and do things online. And with the JavaScript extension, you can also add, I think, TSX True in here. And I think you, it'll give you the ability to add things like divs, but I think they have to be inside some JavaScript here I can't remember here. OK. Let me see, is it in here? OK, doesn't seem to be working, but that's OK. That's how demos go.

Watch more workshops on topic

Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
React Server Components Unleashed: A Deep Dive into Next-Gen Web Development
React Day Berlin 2023React Day Berlin 2023
149 min
React Server Components Unleashed: A Deep Dive into Next-Gen Web Development
Workshop
Maurice de Beijer
Maurice de Beijer
Get ready to supercharge your web development skills with React Server Components! In this immersive, 3-hour workshop, we'll unlock the full potential of this revolutionary technology and explore how it's transforming the way developers build lightning-fast, efficient web applications.
Join us as we delve into the exciting world of React Server Components, which seamlessly blend server-side rendering with client-side interactivity for unparalleled performance and user experience. You'll gain hands-on experience through practical exercises, real-world examples, and expert guidance on how to harness the power of Server Components in your own projects.
Throughout the workshop, we'll cover essential topics, including:- Understanding the differences between Server and Client Components- Implementing Server Components to optimize data fetching and reduce JavaScript bundle size- Integrating Server and Client Components for a seamless user experience- Strategies for effectively passing data between components and managing state- Tips and best practices for maximizing the performance benefits of React Server Components
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
JavaScript-based full-text search with Orama everywhere
Node Congress 2023Node Congress 2023
49 min
JavaScript-based full-text search with Orama everywhere
Workshop
Michele Riva
Michele Riva
In this workshop, we will see how to adopt Orama, a powerful full-text search engine written entirely in JavaScript, to make search available wherever JavaScript runs. We will learn when, how, and why deploying it on a serverless function could be a great idea, and when it would be better to keep it directly on the browser. Forget APIs, complex configurations, etc: Orama will make it easy to integrate search on projects of any scale.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Vite: Rethinking Frontend Tooling
JSNation Live 2021JSNation Live 2021
31 min
Vite: Rethinking Frontend Tooling
Top Content
Vite is a next-generation build tool that leverages native ES modules for improved performance. It eliminates the need for bundling and improves hot module replacement. Vite provides an opinionated default configuration while still allowing advanced customization through plugins. It is framework agnostic and can be used for React and other applications. Vite is being adopted by Next.js and Create React App, and integration with Nuxt 3 offers significant speed improvements.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
Watch video: Debugging JS
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.