Implementing JSX with MithrilJS using WebPack and Babel
In my last post , I went over the basic set up and how to manipulate DOM elements using out of the box syntax provided by Mithril’s framework upon installation. In this article I will go over how to set up and use JSX syntax with Mithril. For those unfamiliar with JSX; JSX (JavaScript XML) is a syntax extension of Javascript created for ReactJS that allows for easier to read (and more similar to vanilla HTML) code. With JSX, code is much easier to read and hop into (especially for those familiar with React).
Core Mithril Syntax:
Mithril With JSX syntax:
Setup
- Create a base project folder, in this case I’m calling it mithril-JSX-setup. Add the following folders like so so your file tree looks like this:
mithril-JSX-setup
|-- src
| |-- index.jsx
|-- .babelrc
|-- index.html
|-- webpack.config.js
- the src folder will the index.jsx file which will act as the location where everything will be rendered from.
- .babelrc is where the JSX will be converted into Javascript thats readable by the browser.
- index.html is the templating of the application.
- and webpack.config.js is where the configuration for WebPack is done.
2) After getting the file tree set up run npm init which will create a package.json file.
3) Remove the code from the package.json file and add this in its place:
4) Run npm install to install all the required dependencies.
5) Navigate to the webpack.config.js file and paste this:
6) Go to the .bablerc file and paste this bit of code that allows for use of JSX in our project.
7) Hop over to the index.html file and paste this:
8) Now lets hop over to index.jsx (make sure it has a .jsx tag and not a .js tag so that its treated as a JSX file) and paste the following code:
9) Lastly, run npm start in the terminal. If everything was entered properly then you should see this displayed in your browser:
With this set up you are now able to write more readable code across all components of your project using JSX syntax! For more information on JSX check out ReactJS’ extensive documentation here.