Skip to content

Commit

Permalink
refactor: Bundle USWDS + custom styles as part of the parcel library …
Browse files Browse the repository at this point in the history
…build (#1275)

**Related Ticket:** #1191
**Related Next.js PR:**
developmentseed/next-veda-ui#20

### Description of Changes
- Bundle USWDS styles and custom styles with our components
- Fix USWDS asset paths to work in Next.js via PostCSS URL handling
- Rename SCSS files to match component names to prevent namespace
conflicts (otherwise they throw `namespace exists` errors when they are
imported into one entry SCSS file)
- Consolidate styles into a single entry point (`styles.scss`)
- Update `yarn.lock` / resolve merge conflicts

### Main problem this PR addresses

When our USWDS-styled components were used in Next.js, they appeared
unstyled because USWDS assets weren't properly bundled. This PR:

1. Bundles all needed USWDS assets with our components
2. Resolves USWDS asset paths correctly in Next.js
3. Makes styles work automatically in Next.js without the need for
manual style imports

The third point is interesting because Next.js detects and loads any CSS
dependencies that Parcel bundled with our components, which I hope makes
the developer experience much smoother. This means we could do this:

```
// Just import the component, styles come automatically once the VEDA UI lib is used
import { Header } from '@veda-ui/lib'
```

And the component will be styled with the VEDA UI styles, instead of
having to:

```
// Had to manually import styles in Next.js app
import '@veda-ui/lib/styles.css'
import { Header } from '@veda-ui/lib'
```

### Notes & Questions About Changes

Few things to note (cc @hanbyul-here @sandrahoang686 @AliceR)

1. This approach only includes USWDS styles that we're actively using in
our components. These styles are managed through our main `styles.scss`
file. This means we're keeping things lightweight by not including
styles for USWDS components we don't use (like the stepper component).
If a Next.js project needs additional USWDS components later, we can
easily add them to `styles.scss` or they could install the USWDS library
and get access to it. This keeps our bundle size small and efficient (we
only ship what we actually need for VEDA)

2. Style organization:

- Main entry point: `app/scripts/styles/styles.scss`
- Component styles should be imported in this entry file, not in the
components. However, they can be kept in the respective component
directory for easier look up
- Next.js apps don't need to install USWDS as a dependency, everything
comes with our components

### Validation / Testing
VEDA UI

1. Check preview deployment
2. Check that USWDS styles work (page header)
3. Check that custom styles work (page header)
4. Confirm icons display correctly (nav chevrons)

Next.js

1. Test locally using
[symlink](https://github.com/NASA-IMPACT/veda-ui/blob/main/docs/development/REGISTRY.md)
with veda-ui branch (`1137-implement-new-ds-page-header`, now merged to
`main`)
2. Check that both USWDS and custom styles work (page header)
3. Check that no manual style imports are needed
  • Loading branch information
dzole0311 authored Dec 10, 2024
2 parents 455a563 + d447521 commit b710dff
Show file tree
Hide file tree
Showing 13 changed files with 298 additions and 33 deletions.
Empty file.
20 changes: 11 additions & 9 deletions app/scripts/components/common/datepicker/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import React, { ReactNode, useRef, useState } from "react";
import { Icon } from "@trussworks/react-uswds";
import { View } from "react-calendar/dist/cjs/shared/types";
import React, { ReactNode, useRef, useState } from 'react';
import { Icon } from '@trussworks/react-uswds';
import { View } from 'react-calendar/dist/cjs/shared/types';
import Calendar from 'react-calendar';
import Tippy from "@tippyjs/react";
import styled from "styled-components";
import Tippy from '@tippyjs/react';
import styled from 'styled-components';

import 'react-calendar/dist/Calendar.css';
import './index.scss';

interface SimpleDatePickerProps {
disabled: boolean;
Expand Down Expand Up @@ -39,7 +38,7 @@ export const SimpleDatePicker = ({
renderTriggerElement,
calendarView,
minDate,
maxDate,
maxDate
}: SimpleDatePickerProps) => {
const [isCalendarOpen, setIsCalendarOpen] = useState(false);
const triggerRef = useRef<HTMLDivElement>(null);
Expand All @@ -54,7 +53,10 @@ export const SimpleDatePicker = ({
};

const handleClickOutside = (event) => {
if (triggerRef.current && !triggerRef.current.contains(event.target as Node)) {
if (
triggerRef.current &&
!triggerRef.current.contains(event.target as Node)
) {
setIsCalendarOpen(false);
}
};
Expand All @@ -67,7 +69,7 @@ export const SimpleDatePicker = ({
disabled,
tipContent,
triggerHeadReference,
selectedDay,
selectedDay
})}
</TriggerWrapper>
{isCalendarOpen && (
Expand Down
2 changes: 0 additions & 2 deletions app/scripts/components/common/page-header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import {
USWDSExtendedNav
} from '$components/common/uswds';
import { LinkProperties } from '$types/veda';
import './styles.scss';

interface PageHeaderProps {
mainNavItems: NavItem[];
subNavItems: NavItem[];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { ComponentType } from 'react';
import { Tip } from '../../tip';
import { LinkProperties } from '$types/veda';
import './styles.scss';
import './logo-container.scss';

/**
* LogoContainer that is meant to integrate in the default
Expand Down
2 changes: 2 additions & 0 deletions app/scripts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import {
externalDatasetsAtom
} from '$components/exploration/atoms/datasetLayers';

import './styles/styles.scss';

// Adding .last property to array
/* eslint-disable-next-line fp/no-mutating-methods */
Object.defineProperty(Array.prototype, 'last', {
Expand Down
6 changes: 6 additions & 0 deletions app/scripts/styles/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@
@use 'usa-icon';
@use 'usa-modal';
@use 'usa-header';

// Custom VEDA UI styles should be added here, so that they can be
// picked up by Parcel and included in the final CSS bundle for the veda-ui library.
@use "../components/common/page-header/page-header.scss";
@use "../components/common/page-header/logo-container/logo-container.scss";
@use "../components/common/datepicker/datepicker.scss";
41 changes: 41 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,41 @@ function copyUswdsImages() {
return uswds.copyImages();
}

// Task that uses Parcel to build the library version of the VEDA UI.
// It specifies the entry file, output directory, and custom Parcel configuration file.
// This task will generate distributable library (`lib` folder) that other projects can consume.
function parcelBuildLib(cb) {
const args = [
'build',
'app/scripts/index.ts',
'--dist-dir=lib',
'--config',
'.parcelrc-lib'
];

const pr = spawn('node', [parcelCli, ...args], {
stdio: 'inherit'
});
pr.on('close', (code) => {
cb(code ? 'Build failed' : undefined);
});
}

// Copy the uswds assets to the veda-ui lib directory.
// This makes things easier for the veda components to consume
// when the veda-ui library is used as a dependency.
function copyUswdsAssetsToLibBundle() {
return gulp
.src(
[
'./node_modules/@uswds/uswds/dist/fonts/**/*',
'./node_modules/@uswds/uswds/dist/img/**/*'
],
{ base: './node_modules/@uswds/uswds/dist' }
)
.pipe(gulp.dest('lib'));
}

// Below are the parcel related tasks. One for the build process and other to
// start the development server.

Expand Down Expand Up @@ -146,5 +181,11 @@ const parallelTasks =
? gulp.parallel(copyFiles, copyUswdsImages)
: gulp.parallel(copyFiles, copyNetlifyCMS, copyUswdsImages);

module.exports.buildlib = gulp.series(
clean,
copyUswdsAssetsToLibBundle,
parcelBuildLib
);

// Task orchestration used during the production process.
module.exports.default = gulp.series(clean, parallelTasks, parcelBuild);
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"scripts": {
"serve": "NODE_ENV=development gulp serve",
"build": "NODE_ENV=production gulp",
"buildlib": "gulp clean && parcel build 'app/scripts/index.ts' --dist-dir='lib' --config '.parcelrc-lib'",
"buildlib": "gulp buildlib",
"stage": "yarn buildlib && NODE_ENV=staging gulp",
"clean": "gulp clean",
"lint": "yarn lint:scripts && yarn lint:css",
Expand Down Expand Up @@ -179,6 +179,8 @@
"framer-motion": "^10.12.21",
"geojson-validation": "^1.0.2",
"google-polyline": "^1.0.3",
"gulp-postcss": "^10.0.0",
"gulp-sass": "^6.0.0",
"history": "^5.1.0",
"intersection-observer": "^0.12.0",
"jest-environment-jsdom": "^28.1.3",
Expand All @@ -199,6 +201,7 @@
"postcss-import": "^16.1.0",
"postcss-safe-parser": "^7.0.0",
"postcss-scss": "^4.0.9",
"postcss-url": "^10.1.3",
"prop-types": "^15.7.2",
"qs": "^6.10.3",
"qs-state-hook": "^2.0.0",
Expand All @@ -223,6 +226,7 @@
"react-virtual": "^2.10.4",
"recharts": "2.1.12",
"rodemirror": "^2.0.0",
"sass": "^1.81.0",
"scrollama": "^3.1.0",
"shpjs": "^4.0.4",
"styled-components": "^5.3.3",
Expand Down
16 changes: 15 additions & 1 deletion postcss.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
const plugins = [require('autoprefixer'), require('postcss-import')];
const url = require('postcss-url');

const plugins = [
require('autoprefixer'),
require('postcss-import'),
// USWDS SCSS files use relative paths like '../fonts/' to reference assets
// When we compile these SCSS files, PostCSS needs to resolve these paths
// We convert '../' to './' because the final './' paths work correctly in
// Next.js when it resolves paths relative to the built CSS file in node_modules/veda-ui/lib/
url({
url: (asset) => {
return asset.url.replace('../', './');
}
})
];

module.exports = {
syntax: 'postcss-scss',
Expand Down
Loading

0 comments on commit b710dff

Please sign in to comment.