Skip to content

Commit

Permalink
chore: performance improvements
Browse files Browse the repository at this point in the history
- update build asset handling. delete the asset paths manifest since that is an artifact of the build.
- Remove `--use` flag from postcss command. Set env for federalist command.

The `--use` flag in the postcss command was causing issues with inline source maps. By updating the command, we ensure better compatibility and cleaner builds.

- Set ELEVENTY_ENV to production for federalist script
prevent blank space in rendered HTML file output and delete preload
- Write uswds fonts to manifest file so they can be preloaded

Added logic to include .woff2 font files in asset path generation. The new code filters and maps font files, preserving consistent naming and paths, then integrates them into the existing assets object. This ensures all necessary assets, including fonts, are correctly referenced in the output JSON.

- Preload fonts needed for the critical rendering path
- add build step to packages to avoid an unstyled page on the first run of `dev`
- add uswds-init.js to a file that is in the build pipeline so it can be hashed and cached.
- split getFonts out to its own function.
- remove comment
- update production build name
  • Loading branch information
ethangardner authored and drewbo committed Oct 25, 2024
1 parent db4c632 commit c714326
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 33 deletions.
3 changes: 0 additions & 3 deletions .eleventy.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ module.exports = function (config) {
// Copy the `admin` folders to the output
config.addPassthroughCopy('admin');

// Copy USWDS init JS so we can load it in HEAD to prevent banner flashing
config.addPassthroughCopy({'./node_modules/@uswds/uswds/dist/js/uswds-init.js': 'assets/js/uswds-init.js'});

// Add plugins
config.addPlugin(pluginRss);
config.addPlugin(pluginNavigation);
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,4 @@ web_modules/
_site
public
node_modules
_data/assetPaths.json
9 changes: 0 additions & 9 deletions _data/assetPaths.json

This file was deleted.

3 changes: 1 addition & 2 deletions _includes/layouts/base.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<!DOCTYPE html>
{% comment %}
This is used for just about every page. It provides the border around the content.
The home page uses wide.html layout, since it extends full width of page
{% endcomment %}

<!DOCTYPE html>

<html lang="en">

{% include "meta.html" %}
Expand Down
17 changes: 14 additions & 3 deletions _includes/meta.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,20 @@
<meta property="og:type" content="article" />
<link rel="canonical" href="{{ page.url }}" />
<meta property="og:url" content="{{ page.url }}" />
<script async="" src="{{ assetPaths['uswds.js'] }} "></script>

<script src="{{ assetPaths['uswds-init.js'] }}"></script>
<!-- CSS
================================================== -->
<link rel="preload" as="style" href="{{ assetPaths['styles.css'] }}" />
<link rel="stylesheet" href="{{ assetPaths['styles.css'] }}" type="text/css" />
<link rel="stylesheet" href="{{ assetPaths['styles.css'] }}" type="text/css" />

{% comment %}
Preload only the files that are needed for the content in the initial viewport. This
will likely include the fonts needed for the navigation, page heading, and the font needed for the
first paragraph of body copy. The `crossorigin` attribute may be required based on the type
of asset you wish to preload in order for the preload to work properly.
{% endcomment %}
<link rel="preload" href="{{ assetPaths['PublicSans-Regular.woff2'] }}" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="{{ assetPaths['PublicSans-Bold.woff2'] }}" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="{{ assetPaths['Latin-Merriweather-Bold.woff2'] }}" as="font" type="font/woff2" crossorigin>

</head>
53 changes: 42 additions & 11 deletions config/buildAssets.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,47 @@ const path = require('path');
const esbuild = require('esbuild');
const { sassPlugin } = require('esbuild-sass-plugin');

async function getFontFiles(assetPath, pathPrefix) {
const assetDirs = await fs.readdir(assetPath, {withFileTypes: true});
const fonts = await Promise.all(
assetDirs.map(async (item) => {
const itemPath = path.join(assetPath, item.name);
const stats = await fs.lstat(itemPath);
if (stats.isFile() && path.extname(item.name) === '.woff2') {
return item.name;
}
return null;
})
);
return fonts.filter(item => item !== null)
.map((file) => {
const {name, ext} = path.parse(file);
const hashedAt = name.lastIndexOf('-');
const originalName = name.slice(0, hashedAt);
const key = `${originalName}${ext}`;
return {[key]: `${pathPrefix}/assets/${file}`};
});
}

async function createAssetPaths() {
let pathPrefix = ''
let pathPrefix = '';

if (process.env.BASEURL) {
pathPrefix = process.env.BASEURL
pathPrefix = process.env.BASEURL;
}

const assetPath = path.join(__dirname, '../_site/assets');
const assetDirs = await fs.readdir(assetPath);
let assetDirs = await fs.readdir(assetPath, { withFileTypes: true });
const fontFiles = await getFontFiles(assetPath, pathPrefix);

assetDirs = assetDirs
.filter((item) => item.isDirectory())
.map((item) => item.name);

const assetsFiles = await Promise.all(
assetDirs.map(async (dir) => {
const files = await fs.readdir(
path.join(__dirname, '../_site/assets', dir)
path.join(__dirname, '../_site/assets', dir),
);
return files.map((file) => {
const { name, ext } = path.parse(file);
Expand All @@ -28,24 +56,27 @@ async function createAssetPaths() {
});
})
);
const assets = Object.assign({}, ...assetsFiles.flat());
const assets = Object.assign({}, ...assetsFiles.flat(), ...fontFiles.flat());
const outputData = path.join(__dirname, '../_data/assetPaths.json');

return await fs.writeFile(outputData, JSON.stringify(assets, null, 2));
}

esbuild
.build({
entryPoints: ['styles/styles.scss', 'js/app.js', 'js/admin.js'],
entryPoints: ['styles/styles.scss', 'js/app.js', 'js/admin.js', 'js/uswds-init.js'],
entryNames: '[dir]/[name]-[hash]',
outdir: '_site/assets',
format: 'iife',
loader: {
'.png': 'dataurl',
'.svg': 'dataurl',
'.ttf': 'dataurl',
'.woff': 'dataurl',
'.woff2': 'dataurl',
'.jpg': 'file',
'.gif': 'file',
'.png': 'file',
'.webp': 'file',
'.svg': 'file',
'.ttf': 'file',
'.woff': 'file',
'.woff2': 'file',
},
minify: process.env.ELEVENTY_ENV === 'production',
sourcemap: process.env.ELEVENTY_ENV !== 'production',
Expand Down
1 change: 1 addition & 0 deletions js/uswds-init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require('../node_modules/@uswds/uswds/dist/js/uswds-init');
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@
"main": "index.js",
"scripts": {
"build": "npm run assets:build && npx @11ty/eleventy",
"assets:autoprefix": "postcss _site/assets/styles/*.css -r --use autoprefixer",
"assets:autoprefix": "postcss _site/assets/styles/*.css -r",
"assets:build": "node ./config/buildAssets && npm run assets:autoprefix",
"assets:clean": "rimraf _site/assets",
"assets:refresh": "npm run assets:clean && npm run assets:build",
"assets:watch": "chokidar 'js/**' 'styles/**' -c 'npm run assets:refresh' --polling",
"clean": "rimraf _site",
"dev": "npm run clean && npm-run-all -p dev:assets dev:serve",
"dev": "npm run clean && npm run assets:build && npm-run-all -p dev:assets dev:serve",
"dev:clean": "npm run clean && npm run dev",
"dev:assets": "npm run assets:refresh && npm run assets:watch",
"dev:debug": "DEBUG=* npx @11ty/eleventy --serve --watch",
"dev:serve": "npx @11ty/eleventy --serve --watch",
"dev:cms": "npx decap-server",
"federalist": "npm run build",
"pages": "ELEVENTY_ENV=production npm run build",
"serve": "npx @11ty/eleventy --serve",
"start": "npx @11ty/eleventy --serve",
"test": "echo \"Error: no test specified\" && exit 1"
Expand Down
8 changes: 6 additions & 2 deletions postcss.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
module.exports = {
plugins: [require('autoprefixer')],
};
plugins: [
require('autoprefixer')({
map: process.env.ELEVENTY_ENV !== 'production'
}),
],
};

0 comments on commit c714326

Please sign in to comment.