vue3入门48 - Vite 进阶 - esbuild使用

306 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第27天,点击查看活动详情

esbuild使用

  • 安装 esbuild
yarn add esbuild
  • 创建 index.js 文件
import React from "react";
React.createElement("div");
function hello() {
  console.log("hello esbuild");
}

hello();
  • 编译文件,
npx esbuild index.js --outfile=dist.js

输出代码与文件无异

import React from "react";
React.createElement("div");
function hello() {
  console.log("hello esbuild");
}

hello();
  • 把第三方库打包到代码里
npx esbuild index.js --outfile=dist.js --bundle  
  • --outfile 输出文件

  • --outdir 输出目录

  • --bundle 打包(会删除无用代码)

  • --target 指定编译目标 --target=esnext

  • --platform 指定编译目标 --platform=node

  • --format 指定编译格式 --format=cjs

  • --watch 监听文件改变

  • --define 指定环境变量 --define:TEST=12

  • --loader 指定解析器(需要开启bundle) --loader:.png=dataurl

  • esbuild 中无法识别 js 中的 dom,需要使用 jsx

    • 默认编译成 React.createElement 的代码
    • --jsx-factory=myJsxFactory 指明其他编译方法
// import React from "react";
import pkg from "./package.json";
import logo from "./logo.png";
import "./index.css";
// const div = React.createElement("div");
function hello() {
  console.log("hello esbuild");
}
console.log(TEST, logo, pkg);
hello();
const div = <div>Hello</div>;
console.log(div);
export default hello;

esbuild 插件的开发方式

在 node 中调用 esbuild 的方法

require("esbuild")
.build({
  entryPoints: ["index.jsx"],
  bundle: true,
  outdir: "dist",
  loader: {
    ".png": "dataurl",
  },
})
.catch(() => process.exit(1));

插件开发

  • 解析 txt 文件
let exampleOnLoadPlugin = {
  name: "example",
  setup(build) {
    let fs = require("fs");
    // 获取 esbuild 配置,可以对配置进行修改
    console.log(build.initialOptions);
    // build.initialOptions.outdir = "lib"; // setup 这里会立即修改配置,其他地方不会修改

    // 告诉 esbuild 对于某一类型的文件应该如何处理他
    build.onResolve({ filter: /\.txt$/ }, async (args) => {
      console.log(args);
      return {
        path: args.path,
        namespace: "txt",
      };
    });
    // Load ".txt" files and return an array of words
    // filter 查找要执行的文件,推荐使用正则,会去 go 语言中执行,提高性能
    // filter: /\.txt$/
    // 如果 onResolve 中做了 namespace,就可以通过 namespace 来过滤需要处理的文件
    build.onLoad({ filter: /\.*/, namespace: "txt" }, async (args) => {
      let text = await fs.promises.readFile(args.path, "utf8");
      console.log(text);
      return {
        // contents 对文件内容的预处理
        // 不推荐在 onLoad 中做太重的处理,因为会导致编译变慢,比如 babel
        // contents: `export default ${JSON.stringify(text.split(/\s+/))}`,
        contents: JSON.stringify(text.split(/\s+/)),
        // 加载器, 如果不使用加载器,使用 export default 把文件导出效果是一样的
        loader: "json",
      };
    });
  },
};

require("esbuild")
  .build({
    entryPoints: ["index.jsx"],
    bundle: true,
    outdir: "dist",
    loader: {
      ".png": "dataurl",
    },
    plugins: [exampleOnLoadPlugin],
  })
  .catch(() => process.exit(1));