Home Web Front-end JS Tutorial Web Development Without (Build) Tooling

Web Development Without (Build) Tooling

Aug 05, 2024 pm 07:11 PM

Web Development Without (Build) Tooling

When starting a new web project where JavaScript will be used, often the first thing we do is set up build and developer tooling. For example, Vite, which is a popular these days. You might not be aware that complicated build tooling it not needed for all JavaScript (web) projects. In fact, it is now easier to go without than ever before as I will show in this article.

Create a new project with an index.html file.

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <p>Hello world</p>
  </body>
</html>
Copy after login

If you are using VS Code, install the Live Preview extension. Run it. This is a simple file server with live reload. You can use any file server, Python comes with one built in:

python3 -m http.server
Copy after login

I like Live Preview, because it automatically refreshes the page after making changes to a file.

You should now be able to access your index.html file from the browser and see "Hello world".

Next, create an index.js file:

console.log("Hello world");

export {};
Copy after login

Include it in your index.html:

<script type="module" src="./index.js"></script>
Copy after login

Open the developer console in your browser. If you see "Hello world", you know that it is loading properly.

Browsers support ECMAScript modules now. You can import other files for their side effects:

import "./some-other-script.js";
Copy after login

or for their exports

import { add, multiply } "./my-math-lib.js";
Copy after login

Pretty cool right? Refer to the MDN guide above for more information.

Packages

You probably don't want to re-invent the wheel, so your project will probably use some third-party packages. That doesn't mean you now need to start using a package manager.

Say we want to use superstruct for data validation. We can can not just load modules from our own (local) file server, but from any URL. esm.sh conveniently provides modules for almost all packages available on npm.

When you visit https://esm.sh/superstruct you can see that you are re-directed to the latest version. You can include this package as follows in your code:

import { assert } from "https://esm.sh/superstruct";
Copy after login

If you want to be on the safe side, you can pin versions.

Types

I don't know about you, but TypeScript spoiled me (and made me lazy). Writing plain JavaScript without help from the type checker feels like writing over a tightrope. Luckily, we don't have to forgo type checking either.

It is time to bust out npm (even though we won't ship any code it provides).

npm init --yes
npm install typescript
Copy after login

You can use the TypeScript compiler on JavaScript code just fine! There is first-class support for it. Create a jsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "checkJs": true,
    "allowJs": true,
    "noImplicitAny": true,
    "lib": ["ES2022", "DOM"],
    "module": "ES2022",
    "target": "ES2022"
  },
  "include": ["**/*.js"],
  "exclude": ["node_modules"]
}
Copy after login

Now run

npm run tsc --watch -p jsconfig.json
Copy after login

and make a type error in your code. The TypeScript compiler should complain:

/** @type {number} **/
const num = "hello";
Copy after login

By the way, the comment you see above is JSDoc. You can annotate your JavaScript with types this way. While it is a little bit more verbose than using TypeScript, and you get used to it pretty quickly. It is also very powerful, as long as you are not writing crazy types (which you should not for most projects) you should be fine.

If you do need a complicated type (helper), you can always add some TypeScript in a .d.ts file.

Is JSDoc just a stepping stone for people stuck with large JavaScript projects to be able to gradually migrate gradually to TypeScript? I don't think so! The TypeScript team also continues to add great features to JSDoc + TypeScript, such as in the upcoming TypeScript release. Auto-completion also works great in VS Code.

Import maps

We learned how to add external packages to our project without a build tool. However, if you split your code in a lot of modules, writing out the complete URL over and over again might be a bit verbose.

We can add an import map to the head section of our index.html:

<script type="importmap">
  {
    "imports": {
      "superstruct": "https://esm.sh/superstruct@1.0.4"
    }
  }
</script>
Copy after login

Now we can simply import this package with

import {} from "superstruct"
Copy after login

Like a 'normal' project. Another benefit is that completion and recognition of types will work as expected if you install the package locally.

npm install --save-dev superstruct
Copy after login

Note that the version in your node_modules directory will not be used. You can remove it, and your project will continue to run.

A trick I like to use is to add:

      "cdn/": "https://esm.sh/",
Copy after login

To my import map. Then any project available through esm.sh can be used by simply importing it. E.g.:

import Peer from "cdn/peerjs";
Copy after login

If you want to pull types from node_modules for development for this type of import as well, you need to add the following to the compilerOptions of your jsconfig.json:

    "paths": {
      "cdn/*": ["./node_modules/*", "./node_modules/@types/*"]
    },
Copy after login

Deployment

To deploy your project, copy all the files to a static file host and you are done! If you have ever worked on a legacy JavaScript project, you know the pain of getting build tooling updated that is not even 1-2 years old. Your will not suffer the same fate with this project setup.

Testing

If your JavaScript does not depend on browser APIs, you could just use the test runner that comes bundled with Node.js. But why not write your own test runner that runs right in the browser?

/** @type {[string, () => Promise<void> | void][]} */
const tests = [];

/**
 *
 * @param {string} description
 * @param {() => Promise<void> | void} testFunc
 */
export async function test(description, testFunc) {
  tests.push([description, testFunc]);
}

export async function runAllTests() {
  const main = document.querySelector("main");
  if (!(main instanceof HTMLElement)) throw new Error();
  main.innerHTML = "";

  for (const [description, testFunc] of tests) {
    const newSpan = document.createElement("p");

    try {
      await testFunc();
      newSpan.textContent = `✅ ${description}`;
    } catch (err) {
      const errorMessage =
        err instanceof Error && err.message ? ` - ${err.message}` : "";
      newSpan.textContent = `❌ ${description}${errorMessage}`;
    }
    main.appendChild(newSpan);
  }
}

/**
 * @param {any} val
 */
export function assert(val, message = "") {
  if (!val) throw new Error(message);
}
Copy after login

Now create a file example.test.js.

import { test, assert } from "@/test.js";

test("1+1", () => {
  assert(1 + 1 === 2);
});
Copy after login

And a file where you import all your tests:

import "./example.test.js";

console.log("This should only show up when running tests");
Copy after login

Run this on page load:

await import("@/test/index.js"); // file that imports all tests
(await import("@/test.js")).runAllTests();
Copy after login

And you got a perfect TDD setup. To run only a section of the tests you can comment out a few .test.js import, but test execution speed should only start to become a problem when you have accumulated a lot of tests.

Benefits

Why would you do this? Well, using fewer layers of abstraction makes your project easier to debug. There is also the credo to "use the platform". The skills you learn will transfer better to other projects. Another advantage is, when you return to a project built like this in 10 years, it will still just work and you don't need to do archeology to try to revive a build tool that has been defunct for 8 years. An experience many web developers that worked on legacy projects will be familiar with.

See plainvanillaweb.com for some more ideas.

The above is the detailed content of Web Development Without (Build) Tooling. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

See all articles