For those of you who have used Vite, you know that Vite is a developer environment that uses ESBuild to compile code and a build environment that uses rollup. If you want to see rollup, you can check out my previous articles. Rollup section 1 rollup Section 2 Rollup section 2 Rollup

use

There are three ways to use esBuild: CLI, JS, and Go

Setting up the development environment

NPM install esbuild -d: NPM install esbuild -d: NPM install esbuild -d: NPM install esbuild -d Esbuild does not provide configuration files like WebPack and Rollup. Instead, it provides conversion functions (executed in node or Go) to convert code directly.

I am a front-end development engineer, do not know about GO, here only do JS two ways to configure the development environment.

Methods acli

Using cli this, like webpCK and rollup, gives us a lot of instructions: –bundle –w –outfile, etc.

Add the following script to the script in package.json: “build”: Esbuild SRC /index.js –bundle –outdir=dist/index.js” esbuild load SRC /index.js as entry, bundle and dist/index.js as exit.

The effect

Mode 2 Useapi

Create esbuild.config.js in SRC. This js is not a configuration file, but a way to call it using the API.

const esbuildConig = () = > require('esbuild').buildSync({
  entryPoints: ['src/index.js'].bundle: true.outfile: 'out.js'
})

esbuildConig();
Copy the code

Create a new script in package.json as follows:

"buildConfig": "node ./esbuild.config.js"# here is node to execute that JS, and then package and translate it through the APICopy the code

Compile the results

Start the development service

Esbuil itself provides an external startup service, but I wanted to compile it directly and manually start a static resource service that automatically refreshes the browser when the code changes. The main files are TS and CSS files.

Results the following

After the service is started: After the service is started, we can access our project and then when we modify the code later. Automatically update the browser.

After service suspension: Is this familiar after service disconnection?

Train of thought

Esbuild’s job is simple: package resources quickly. Compile the resource, which stands for Babel. It’s quite comfortable to use in the development phase. Debugging code is easy.

Step 1: Package the development environment code

Esbuild provides several key translation functions, so we can use build. In order to facilitate us to see the content, so we also generate the code of the development environment to the local (generally does not generate the code, after packaging the code to read and write from the local, vite, Webpack, etc., are packed in memory).

Step 2: Start a service

Esbuild itself will be able to provide services, but the documentation is not clear, and the Vite development environment is also using KOA to provide services, so we should use KOA to provide services. And easy to generate index.html file binding corresponding JS and CSS.

Step 2: Listen for file changes and notify the browser of updates

There is one point to distinguish here, that is, the hot update implemented by Vite and Webpack is HMR (Hot Module Reload), while HRM retains the current state and automatically updates local pages without refreshing the whole page. Please check the specific ideas. We’re not going to do that here, just change the code and I’ll refresh the browser for you. Experience the esbuild development process.

The core code is as follows

/ / esbuild. Config. Js file
const esbuild = require('esbuild');
const serve = require('koa-static');
const Koa = require('koa');
const path = require('path');
const fse = require('fs-extra')
const app = new Koa();

// Start automatically refresh the browser after compiling
const livereload = require('livereload');
const lrserver = livereload.createServer();
lrserver.watch(__dirname + "/dist");

// Use static services
app.use(serve((path.join(__dirname + '/dist'))));

esbuild.build({
  / / the entry
  entryPoints: ['src/index.ts']./ / start sourcemap
  sourcemap: true./ / packaging
  bundle: true.// Output directory
  outfile: 'dist/index.js'.// Enable the listening mode of polling
  watch: {
    onRebuild(error, result) {
      if (error) console.error('watch build failed:', error)
      else {
        // To automatically open the browser and update the browser
        console.log('\x1B[36m%s\x1B[39m'.'watch build succeeded')
      }
    },
  },
}).then(async res => {
  const fileName = path.join(__dirname + '/dist/index.html');
  // Create a file, if the file does not exist directly create, do not do anything
  await fse.ensureFile(fileName);
  // Write the following contents to the index.html file in dist
  await fse.writeFileSync(fileName, ` 
         
       
       
         

app
`

) // Start a KOA static resource service app.listen(3000.() = > { console.log(`> Local: http://localhost:3000/`)})})Copy the code

Here is just the key code and the train of thought, specific look at: https://github.com/cll123456/myPackage/tree/esbuild-dev

Other instructions

Simple options: define:K=V Substitute Kwith V whileParsing # Replace K --external:M Exclude with V during parsingmodule M fromThe bundle (can use * wildcards) # format=... Output format (iife | cjs | esm, nodefault when not 
                        bundling, otherwise defaultIs iife the when platform is browser and CJS when platform is the node) # output file format (iife | CJS | esm, don't pack the default, --loader:X= Use loader L to load file extension X, where L is oneof: Js | JSX | | ts TSX | json | text | base64 | file | dataurl | binary # when L is one of the following documents (js | JSX | | ts TSX | json | text | Base64 | file | dataurl | binary) use loader L to expand X - minify minify the output (sets all - minify - * flags) # code compression (set all to use - minify - *) - outdir =... The output directory (forMultiple entry points) # File output directory (for multiple entry points) --outfile=... The output file (for# File output name (for a single entry point) --platform=... Platform target (browser | node | neutral,defaultBrowser) # compiler environment (browser | node | neutral, the default browser) - serve =... Start a local HTTP server onthis host:port forOutputs # open a HTTP service based on host:port to Emit a sourcemap # output sourcemap file --splitting Enable code splitting  (currently onlyforEsm) # Code split (currently esM mode only) --target=... Environment target (e.g. es2017, chrome58, firefox57, safari11, edge16, node10,defaultEsnext (e.g. es2017, chrome58, firefox57, safari11, edge16, node10, default esnext syntax) Rebuild on file system changes --allow-overwrite allow output files to overwrite input files --asset-names=... Path template to usefor "file" loader files
                            (default "[name]-[hash]"# static resource output file name (default is the name plus hash) --banner:T=... Text to be prepended to each output fileof type T
                            where T is one ofOutput: CSS | js # in js, CSS file to add a text - charset = utf8 Do notescape UTF-8Do not do other conversions, default (UTF -)8) - the chunk - names =... Path template to usefor code splitting chunks
                            (default "[name]-[hash]"/ / error: error: error: error: error: error: error: error: error: error: error: error Force useof color terminal escapes (true | false) # Terminal output with color --entry-names=... Path template to usefor entry point output paths 
                            (default "[dir]/[name]", can also use "[hash]"Path template (default dir/hash, also hash) --footer:T=... Text to be appended to each output fileof type T
                            where T is one of| js, CSS # # in the output of js, CSS file add a text, in the endglobal-name=...         The name of the global forThe IIFE format # output file type is IIFE global name --inject:F Import the file F into all input files and automatically replace matching  globalswithImports # imports file F into all input files and automatically replaces the matching global variable -- jsX-Factory =... What to usefor JSX instead ofReact.createElement # JSX react. createElement --jsx-fragment=... What to usefor JSX instead ofReact.Fragment # JSX react. Fragment -- JSX =...Set to "preserve"To disable transforming JSX to JS # set to "preserve" to disable converting JSX to JS --keep-names Preserve"name"On functions and classes # keep the names of functions and classes --legal-comments=... Where to place license comments (none | inline | eof | linked | external,defaultEof when bundling and inline otherwise) Disable logging (verbose | debug | info | warning | error | silent,defaultInfo) # console log output form --log-limit=... Maximum message count or0 to disable (default 10) # maximum number of messages --main-fields=... Override the main file orderin package.json
                            (default "browser,module,main" when platform is
                            browser and "main,module"When platform is node) # overwrite fields in package.json. Write metadata about the build to aJSONFile # Write metadata to compiled JSON file --minify-whitespace Remove whitespaceinOutput files # Remove whitespace from output files --minify-identifiers Shorten identifiersinOutput files # shorten the identifier in output files --minify-syntax Use equivalent but shorter syntaxinOutput files # Use the equivalent but shorter syntax -- out-of-extension :.js=.mjs Use a custom output extension insteadof ".js"# replace the output js suffix with a custom suffix --outbase=... The base path used to determine entry point output paths (forMultiple entry points) # Root path to output files (for multiple entry points) --preserve-symlinks Disable symlink resolutionfor moduleLookup # Disable symbolic link parsing --public-path=...Set the base URL for the "file"--pure:N Mark the name Nas a pure function for tree shaking# will mark the name asNThe pure function oftree shaking
  --resolve-extensions=...  A comma-separated list of implicit extensions
                            (default ".tsx,.ts,.jsx,.js,.css,.json") # an implicit comma-separated extended list --servedir=...            What to serve in addition to generated output filesThe output directory of the service extra generated file --source-root=...         Sets the "sourceRoot" field in generated source maps# set in the generated source mapsourceRoot"Field -sourcefile=...          Set the source file for the source map (for stdin) # Set the source file for the source mapping (forstdin) -sourcemap=external      Do not link to the source map with a comment# Comments do not need to be linked tosource map
  --sourcemap=inline        Emit the source map with an inline data URL# Use inline dataURLGenerate the source map --sources-content=false   Omit "sourcesContent" in generated source maps# omit from generated source mappingsourcesContent
  --tree-shaking=...        Set to "ignore-annotations" to work with packages
                            that have incorrect tree-shaking annotations# set to "ignore comments" to handle those with incorrect valuestree-shakingAnnotated package --tsconfig=...            Use this tsconfig.json file instead of other ones# using thistsconfig.jsonDocuments rather than other documentsversion                 Print the current version (0.1216.) and exitPrint the current version and exitCopy the code

Learning a knowledge point, need input and output, so that they can master more, reading documents is an input process, but writing blog is an output process, I hope more people can use this method to learn, science and technology power, come on!!