Create React folder in www with this code:
# Create a project folder
mkdir jsx-modules
cd jsx-modules
# Create an npm project without prompts (-y)
npm init -y
# Install babel
npm install @babel/cli @babel/core @babel/plugin-transform-react-jsx
Next we’ll need a .babelrc
which will tell babel how to process our jsx.
{
"plugins": [
["@babel/plugin-transform-react-jsx", { "pragma": "createElement", "pragmaFrag": "'fragment'" }]
],
"comments": false
}
And then add an index.jsx
file
// A jsx pragma method to create html dom elements
function createElement(tag, props, ...children) {
if (typeof tag === "function") return tag(props, children)
const element = document.createElement(tag)
Object.entries(props || {}).forEach(([name, value]) => {
if (name.startsWith('on') && name.toLowerCase() in window)
element.addEventListener(name.toLowerCase().substr(2), value)
else element.setAttribute(name, value.toString())
})
children.forEach((child) => {
appendChild(element, child)
})
return element
}
const appendChild = (parent, child) => {
if (Array.isArray(child))
child.forEach((nestedChild) => appendChild(parent, nestedChild))
else
parent.appendChild(
child.nodeType ? child : document.createTextNode(child)
)
}
const createFragment = (props, ...children) => {
return children
}
// Setup some data
const name = 'Geoff'
const friends = ['Sarah', 'James', 'Hercule']
// Create some dom elements
const app = (
<div className="app">
<h1 className="title"> Hello, world! </h1>
<p> Welcome back, {name} </p>
<p>
<strong>Your friends are:</strong>
</p>
<ul>
{friends.map(name => (
<li>{name}</li>
))}
</ul>
</div>
)
// Render our dom elements
window.document.getElementById('app').replaceWith(app)
Now you can run this command to generate your javascript.
npx babel index.jsx -d dist
Which will create a new dist/index.js
file with the transpilled code.
You can add
// eslint-disable-next-line no-unused-vars
to ignore annoying eslint errors
And to test our code, add an index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>jsx WITHOUT react</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css"
/>
</head>
<body>
<div id="app"></div>
<script src="dist/index.js"></script>
</body>
</html>
I snuck in water.css to make raw html prettier.