esbuild打包速度非常快(esbuild比Webpack快100倍),目前我所在公司项目也开始将之前我写的webpack-demo方案逐渐替换到esbuild splitting多页面打包。
初始化项目
mkdir esbuild-splitting
cd esbuild-splitting
yarn --init
安装依赖
yarn global add serve
yarn add del gulp gulp-changed gulp-esbuild jquery
项目文件
项目目录结构如下:
├─dist
│ └─js
└─src
├─html
└─js
src/html
文件夹中分别放入a.html
、b.html
,html.zip解压方进入吧。
src/js/core.js
import $ from "jquery";
$("#core").html("Core module");
src/js/a.js
import $ from "jquery";
import "./core";
$("#a").html("A file, file A");
$('body').css('color','red')
src/js/b.js
import $ from "jquery";
import "./core";
$("#b").html("B yourself");
gulpfile.js
const gulp = require('gulp')
const {createGulpEsbuild} = require('gulp-esbuild')
const gulpEsbuild = createGulpEsbuild({ incremental: true })
const changed = require('gulp-changed')
const del = require('del')
function clean() {
// You can use multiple globbing patterns as you would with `gulp.src`,
// for example if you are using del 2.0 or above, return its promise
return del(['dist'])
}
function script() {
return gulp.src('./src/js/*.js')
.pipe(gulpEsbuild({
bundle: true,
splitting:true,
format:'esm',
minify: true
}))
.pipe(gulp.dest('./dist/js'))
}
function html() {
return gulp.src('./src/html/**/*.html')
.pipe(changed('./dist/*.html'))
.pipe(gulp.dest('./dist'))
}
function watch() {
gulp.watch('./src/js', script)
gulp.watch('./src/html/**/*.html', html)
}
// const build = gulp.series(clean, gulp.parallel(script, watch))
const build = gulp.series(gulp.parallel(script,html, watch))
exports.clean = clean
exports.script = script
exports.html = html
exports.watch = watch
exports.build = build
exports.default = build
package.json
package.json
中增加:
"scripts": {
"watch": "gulp watch",
"serve": "serve dist -p 3000"
}
编译和查看效果
编译:
gulp
查看效果:
serve