首页  >  文章  >  web前端  >  无需(构建)工具的 Web 开发

无需(构建)工具的 Web 开发

WBOY
WBOY原创
2024-08-05 19:11:221093浏览

Web Development Without (Build) Tooling

当启动一个将使用 JavaScript 的新 Web 项目时,我们做的第一件事通常是设置构建和开发人员工具。比如现在很流行的Vite。您可能不知道并非所有 JavaScript(Web)项目都需要复杂的构建工具。事实上,正如我将在本文中展示的那样,现在比以往任何时候都更容易摆脱困境。

使用index.html 文件创建一个新项目。

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <p>Hello world</p>
  </body>
</html>

如果您使用的是 VS Code,请安装实时预览扩展。运行它。这是一个具有实时重新加载功能的简单文件服务器。您可以使用任何文件服务器,Python 内置了一个:

python3 -m http.server

我喜欢实时预览,因为它会在更改文件后自动刷新页面。

您现在应该能够从浏览器访问您的index.html 文件并看到“Hello world”。

接下来,创建一个index.js文件:

console.log("Hello world");

export {};

将其包含在您的index.html中:

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

在浏览器中打开开发者控制台。如果您看到“Hello world”,则说明它正在正确加载。

浏览器现在支持 ECMAScript 模块。您可以导入其他文件以消除其副作用:

import "./some-other-script.js";

或用于出口

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

很酷吧?请参阅上面的 MDN 指南了解更多信息。

套餐

您可能不想重新发明轮子,因此您的项目可能会使用一些第三方包。这并不意味着您现在需要开始使用包管理器。

假设我们想使用超级结构进行数据验证。我们不仅可以从我们自己的(本地)文件服务器加载模块,还可以从任何 URL 加载模块。 esm.sh 方便地为 npm 上可用的几乎所有包提供模块。

当您访问 https://esm.sh/superstruct 时,您可以看到您被重定向到最新版本。您可以在代码中包含此包,如下所示:

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

如果您想安全起见,您可以固定版本。

类型

我不了解你,但 TypeScript 宠坏了我(并且让我变得懒惰)。在没有类型检查器帮助的情况下编写纯 JavaScript 感觉就像走钢丝一样。幸运的是,我们也不必放弃类型检查。

是时候淘汰 npm 了(尽管我们不会发布它提供的任何代码)。

npm init --yes
npm install typescript

您可以在 JavaScript 代码上使用 TypeScript 编译器!它有一流的支持。创建 jsconfig.json:

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

现在运行

npm run tsc --watch -p jsconfig.json

并在代码中犯一个类型错误。 TypeScript 编译器应该抱怨:

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

顺便说一下,你上面看到的评论是 JSDoc。您可以通过这种方式用类型注释您的 JavaScript。虽然它比使用 TypeScript 更冗长一些,但你很快就会习惯它。它也非常强大,只要您不编写疯狂的类型(对于大多数项目来说您不应该这样做),您应该没问题。

如果您确实需要复杂的类型(助手),您可以随时在 .d.ts 文件中添加一些 TypeScript。

JSDoc 是否只是那些陷入大型 JavaScript 项目的人们能够逐步迁移到 TypeScript 的垫脚石?我不这么认为! TypeScript 团队还继续向 JSDoc + TypeScript 添加出色的功能,例如即将发布的 TypeScript 版本。自动完成功能在 VS Code 中也非常有效。

导入地图

我们学习了如何在不使用构建工具的情况下将外部包添加到我们的项目中。但是,如果您将代码拆分为许多模块,则一遍又一遍地写出完整的 URL 可能会有点冗长。

我们可以将导入映射添加到我们的index.html的head部分:

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

现在我们可以简单地使用
导入这个包

import {} from "superstruct"

就像一个“正常”项目。另一个好处是,如果您在本地安装该软件包,类型的完成和识别将按预期工作。

npm install --save-dev superstruct

请注意,node_modules 目录中的版本将不会被使用。您可以将其删除,您的项目将继续运行。

我喜欢使用的一个技巧是添加:

      "cdn/": "https://esm.sh/",

到我的导入地图。然后,通过 esm.sh 提供的任何项目都可以通过简单地导入来使用。例如:

import Peer from "cdn/peerjs";

如果您也想从node_modules中提取类型以进行此类导入的开发,则需要将以下内容添加到jsconfig.json的compilerOptions中:

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

部署

要部署您的项目,请将所有文件复制到静态文件主机,然后就完成了!如果您曾经参与过旧版 JavaScript 项目,您就会知道更新不到 1-2 年的构建工具的痛苦。通过此项目设置,您将不会遭受同样的命运。

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);
}

Now create a file example.test.js.

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

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

And a file where you import all your tests:

import "./example.test.js";

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

Run this on page load:

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

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.

以上是无需(构建)工具的 Web 开发的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn