From e0f887525bc3d453011e04009dc1e5d923b7c17d Mon Sep 17 00:00:00 2001 From: Kelvin Oghenerhoro Omereshone Date: Thu, 6 Jun 2024 14:26:45 +0100 Subject: [PATCH] [feat] add asset hashing (#6) * feat: generate and inject script and style tags * feat: change chunk split strategy to split-by-experience --- index.js | 55 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 1298772..22a45d5 100644 --- a/index.js +++ b/index.js @@ -8,13 +8,49 @@ const path = require('path') const { defineConfig, mergeRsbuildConfig } = require('@rsbuild/core') module.exports = function defineShipwrightHook(sails) { + function getManifestFiles() { + const manifestPath = path.resolve( + sails.config.appPath, + '.tmp', + 'public', + 'manifest.json' + ) + const data = require(manifestPath) + const files = data.allFiles + return files + } + function generateScripts() { + const manifestFiles = getManifestFiles() + let scripts = [] + manifestFiles.forEach((file) => { + if (file.endsWith('.js')) { + scripts.push(``) + } + }) + return scripts.join('\n') + } + + function generateStyles() { + const manifestFiles = getManifestFiles() + let styles = [] + manifestFiles.forEach((file) => { + if (file.endsWith('.css')) { + styles.push(``) + } + }) + return styles.join('\n') + } return { + defaults: { + shipwright: { + build: {} + } + }, /** * Runs when this Sails app loads/lifts. */ initialize: async function () { const appPath = sails.config.appPath - const defaultConfigs = defineConfig({ source: { entry: { @@ -26,7 +62,7 @@ module.exports = function defineShipwrightHook(sails) { } }, output: { - filenameHash: false, + manifest: true, distPath: { root: '.tmp/public', css: 'css', @@ -64,13 +100,16 @@ module.exports = function defineShipwrightHook(sails) { }, performance: { chunkSplit: { - strategy: 'all-in-one' + strategy: 'split-by-experience' } }, server: { port: sails.config.port, strictPort: true, printUrls: false + }, + dev: { + writeToDisk: (file) => file.includes('manifest.json') // Write manifest file } }) const config = mergeRsbuildConfig( @@ -80,8 +119,8 @@ module.exports = function defineShipwrightHook(sails) { const { createRsbuild } = require('@rsbuild/core') try { const rsbuild = await createRsbuild({ rsbuildConfig: config }) - if (process.env.NODE_ENV == 'production') { - rsbuild.build() + if (process.env.NODE_ENV === 'production') { + await rsbuild.build() } else { const rsbuildDevServer = await rsbuild.createDevServer() sails.after('hook:http:loaded', async () => { @@ -97,9 +136,13 @@ module.exports = function defineShipwrightHook(sails) { sails.on('lower', async () => { await rsbuildDevServer.close() }) + sails.after('lifted', () => {}) + } + sails.config.views.locals = { + shipwright: { scripts: generateScripts, styles: generateStyles } } } catch (error) { - sails.error(error) + sails.log.error(error) } } }