之前我写的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
分离的代码也会一并引入,非常方便。