esbuild entryPoints多个入口glob实现方案

之前我写的esbuild gulp方案使用的人很多,最近有人问用JS API来做打包脚本。

目录

dist/js/**/*.js
src/js/**/*.js

src/js下面的文件,编译到对应的dist/js目录中。

package.json

{
  "scripts": {
    "start": "npm-run-all --parallel js-compile",
    "js-compile": "nodemon --watch src/js/ --ext *.js build/esbuild.js"
  },
  "dependencies": {
    "@popperjs/core": "^2.11.2",
    "bootstrap": "^5.1.3",
    "esbuild": "^0.14.10",
    "glob": "^7.2.0",
    "jquery": "^3.6.0",
    "lodash": "^4.17.21",
    "nodemon": "^2.0.15",
    "npm-run-all": "^4.1.5"
  }
}

build/esbuild.js

(async () => {
  const glob = require('glob')
  const path = require('path')
  const esbuild = require('esbuild')
  const entryFiles = glob.sync(path.join(__dirname, '../src/js/**/*.js'))
  await esbuild.build({
    entryPoints: entryFiles,
    bundle: true,
    outdir: 'dist/js',
    splitting: true,
    minify: true,
    format: 'esm'
  }).then(result => {
    console.log('watching...')
  })
})()

运行编译

npm run start

页面引入:src="dist/js/index.js"时,splitting分离的代码也会一并引入,非常方便。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注