Created
February 18, 2022 20:08
-
-
Save owen2345/c281dc7e38cfad5bff395af7765a4c7d to your computer and use it in GitHub Desktop.
Esbuild with the ability to define custom entry points and with ability to copy static assets from node modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const fs = require('fs'); | |
const path = require('path'); | |
const esbuild = require('esbuild') | |
// Scan entrypoints | |
function scanFiles(dir, options = {}, result = []) { | |
let { recursive = false, ext = null } = options; | |
fs.readdirSync(dir).forEach(file => { | |
let fullPath = path.join(dir, file); | |
if (fs.lstatSync(fullPath).isDirectory()) { | |
if (recursive) scanFiles(fullPath, options, result); | |
} else { | |
result.push(fullPath); | |
} | |
}); | |
if (ext) result = result.filter(src => src.endsWith(ext)); | |
return result; | |
} | |
// Plugin | |
let copyStaticFiles = (options = {}) =>({ | |
name: 'copyFonts', | |
setup(build) { | |
build.onStart(result => { | |
options.forEach(({ source, target, ext }) => { | |
fs.mkdirSync(target, { recursive: true }); | |
scanFiles(source, { recursive: true, ext: ext }).forEach(path => { | |
const targetFile = `${target}/${path.split('/').pop()}`; | |
fs.writeFileSync(targetFile, fs.readFileSync(path)); | |
}); | |
}); | |
}); | |
}, | |
}); | |
const entrypoints = scanFiles(`${__dirname}/app/assets/javascripts`, { ext: '.js' }); | |
const fontawesome = { | |
source: `${__dirname}/node_modules/@fortawesome/fontawesome-free/webfonts`, | |
target: `${__dirname}/public/assets/awesome_fonts` | |
}; | |
esbuild.build({ | |
entryPoints: entrypoints, | |
sourcemap: true, | |
bundle: true, | |
minify: true, | |
watch: process.argv.includes('--watch'), | |
outdir: 'app/assets/builds', | |
plugins: [copyStaticFiles([fontawesome])], | |
}).catch(() => process.exit(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment