Develop, test, run, and bundle JavaScript & TypeScript projects—all with Bun.
Let's talk about something new in Web Development world which is BUN 1.0
What is Bun?
A JavaScript runtime built from scratch to serve the modern JS ecosystem.
Include native bundles, transpiler, task runner, and npm client.
Written in the ZIG programming languages.
Drop-in replacement for Node.js / Fully compatible with Node APIs.
3 Major Design Goals
Speed: Faster than Node and Deno, Extends the JavaScriptCore Engine, Little Dependencies
Elegant APIs: Minimal Set of highly optimized APIs for performing common tasks.
Cohesive DX: Complete toolkit for both server-side and frontend.
Features and Advantages
Speed and Performance
Drop-in Node Compatibility
Works with node_modules
Native NPM Client
No Module Madness
Web-Standard APIs
TypeScript Out of the Box
JSX
Watch Mode
Environment Variables
Integrated Bundles
SQLite Database
Installation
curl -fsSL
https://bun.sh/install
| bash
Supported on macOS, Linux, and WSL
Now create folder Bun-Crash and open it in VS-Code, open the terminal, and run bun init
and run bun run index.ts
Bun.server()
open index.ts, write this code
const server = Bun.serve({ port:2000, fetch(req){ return new Response('Hello World from Bun'); }, }); console.log(`Listening on port ${server.port}`);
Now open the terminal and run bun run index.ts
Output on Browser: Open any browser and write localhost:2000
Watch Mode
bun --watch index.ts
it is the same as Nodemon, if you change anything in the code it will show on the browser result without reloading the page.
Environment Variable
Create a new file .env and in that write PORT = 2000
and go to index.ts and change the port value to port:process.env.PORT || 8000
OR port:BUN.env.PORT || 8000
Bun Scripts
Change in package.json
"scripts": { "start" : "bun run index.ts", "dev": "bun --watch index.ts" },
Simple Routes || Basic Server API
In index.ts
const server = Bun.serve({ port: Bun.env.PORT || 8000, fetch(req){ const url = new URL(req.url); if(url.pathname === '/') return new Response("Home Page of Bun"); if(url.pathname === '/blog') return new Response("Blog of Bun"); return new Response('Sorry 404!'); }, }); console.log(`listening on port ${server.port}`);
BunX
Run the packages without installing them.
bunx cowsay Hello World Bun
Node Core Modules
In bun now you can also use Node Core Modules.
Create a modules.ts file and write the below code :
import path from 'path'
const filepath = path.join('foo','bar','image.png');
const filename = path.basename(filepath);
console.log(filename);
File I/O API
Create a new file file.ts, and write the below code:
const data = "I love JavaScript Bun";
await Bun.write('output.txt', data);
Now run bun run file.ts,
now you are able to see a new file with the name output.txt created.
Now file read
Write this code:
const file = await Bun.file('output.txt');
console.log(await file.text());
Testing
In Bun now you also write testing, everything in JS in one place.
Create a new file index.test.ts, Now write the below code:
import { describe, expect, test, beforeAll } from "bun:test";
beforeAll( () => {
// setup test
});
describe('math' , () => {
test('addition', () =>{
expect(2+2).toBe(4);
});
});
The Bundler
We can also bundle the Typescript file using Bun. In the below code, I am getting the GitHub user profile data on the front end.
Create src folder -> create index.ts and githubAPI.ts also Install Axios
bun install axios
Inside the githubAPI.ts file write the code :
import axios from 'axios';
async function fetchUser(user){
const res = await axios.get('https://api.github.com/users/' + user);
return res.data
}
export default fetchUser;
index.ts
import fetchUser from "./githubAPI";
(async () =>{
const userData = await fetchUser('Udaichauhan284');
document.querySelector('h1').innerHTML = JSON.stringify(userData);
})();
Now run bun build ./src/index.ts --outfile=./dist/bundle.js
It will create a dist folder with bundle.js inside this file everything from githubAPI.ts and index.ts will be there.
Now inside the dist folder, create an index.html file
output:
React and JSX
We can also use React and JSX with Bun.
Run in terminal bun install react react-dom
This will install react and react-dom in the BUN-CRASH folder.
Now go back to the src folder and rename index.ts to index.tsx, remove the previous code, and write the following code:
import React from 'react';
import {createRoot} from 'react-dom';
const root = createRoot(document.getElementById('root'));
const App = () =>{
const [count,setCount] = React.useState(0);
return (
<div>
<h1>Hello World!</h1>
<h2>Count : {count} </h2>
<button onclick = { () => setCount(count+1)}>Increment</button>
</div>
)
}
root.render(<App/>);
Now go to index.html, write below code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Github Profile</title>
</head>
<body>
<!--<h1>Hello!</h1> -->
<div id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>
Now in the terminal run bun build ./src/index.tsx --outfile=./dist/bundle.js --watch
Refresh the browser index.html, now you will be able to see the output.
Thank You !!! 🙏🏻
For more refer Bun Crash Course by Travery Media.