Skip to content

Commit

Permalink
build: separate dev and prod builds (#2549)
Browse files Browse the repository at this point in the history
Previously we shipped only one distribution, which could be used for any purpose. We now
provide both a production and a development build. The production build is minified and any
warning (usually printed to the console) is removed.

---------

Co-authored-by: Jeremias Peier <[email protected]>
  • Loading branch information
kyubisation and jeripeierSBB authored Apr 8, 2024
1 parent df612ab commit 909b2e0
Show file tree
Hide file tree
Showing 14 changed files with 87 additions and 36 deletions.
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@
"private": true,
"scripts": {
"postinstall": "yarn playwright install",
"build:components": "vite build --config src/components/vite.config.ts",
"build:react": "vite build --config src/react/vite.config.ts",
"build:components": "npm-run-all --sequential build:components:*",
"build:components:production": "vite build --config src/components/vite.config.ts",
"build:components:development": "NODE_ENV=development vite build --mode development --config src/components/vite.config.ts",
"build:react": "npm-run-all --sequential build:react:*",
"build:react:production": "vite build --config src/react/vite.config.ts",
"build:react:development": "NODE_ENV=development vite build --mode development --config src/react/vite.config.ts",
"build:storybook": "storybook build --quiet --output-dir dist/storybook --stats-json",
"build": "npm-run-all --sequential build:components build:react build:storybook",
"docs": "npm-run-all --sequential docs:manifest docs:to-md",
Expand Down
4 changes: 1 addition & 3 deletions src/components/core/styles/core/functions.scss
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
@use 'sass:math';

/**
* size: value in px (no unit)
*/
@function px-to-rem-build($size) {
/* size: value in px (no unit) */
@return ((math.div($size, 16)) * 1rem);
}
2 changes: 1 addition & 1 deletion src/components/core/styles/core/mediaqueries.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

@use 'sass:math';
@use 'sass:string';
@use '@sbb-esta/lyne-design-tokens/dist/scss/sbb-variables.scss' as sbb-tokens;
@use 'node_modules/@sbb-esta/lyne-design-tokens/dist/scss/sbb-variables.scss' as sbb-tokens;

$mq-breakpoints: (
zero: sbb-tokens.$sbb-breakpoint-zero-min,
Expand Down
2 changes: 1 addition & 1 deletion src/components/form-field/form-field/form-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class SbbFormFieldElement extends SbbNegativeMixin(LitElement) {

private _onSlotLabelChange(): void {
const labels = Array.from(this.querySelectorAll('label'));
if (labels.length > 1) {
if (import.meta.env.DEV && labels.length > 1) {
console.warn(
`Detected more than one label in sbb-form-field#${this.id}. Only one label is supported.`,
);
Expand Down
21 changes: 10 additions & 11 deletions src/components/image/image.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,29 +49,29 @@ export default (jsonString: string): InterfaceImageAttributesSizesConfigBreakpoi
}

// make sure that we have `breakpoints` key in object
const errorMessage =
'sbb-image error: attribute breakpoints has wrong data format. Reference the documentation to see how you should format the data for this attribute.';

const logWarning = import.meta.env.DEV
? () =>
console.warn(
'sbb-image error: attribute breakpoints has wrong data format. Reference the documentation to see how you should format the data for this attribute.',
)
: null;
let jsonObject: InterfaceImageAttributesSizesConfig;

try {
jsonObject = JSON.parse(jsonString);
} catch (error) {
console.warn(errorMessage);

logWarning?.();
return [];
}

if (!jsonObject.breakpoints || jsonObject.breakpoints.length === 0) {
console.warn(errorMessage);

logWarning?.();
return [];
}

// make sure we get an array of breakpoints
if (!Array.isArray(jsonObject.breakpoints)) {
console.warn(errorMessage);

logWarning?.();
return [];
}

Expand Down Expand Up @@ -101,8 +101,7 @@ export default (jsonString: string): InterfaceImageAttributesSizesConfigBreakpoi
});

if (wrongKeyDetected || missingKeyDetected) {
console.warn(errorMessage);

logWarning?.();
return [];
}

Expand Down
10 changes: 6 additions & 4 deletions src/components/tabs/tab-group/tab-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ export class SbbTabGroupElement extends LitElement {

this._tabContentResizeObserver.observe(tab.relatedContent!);
this._selectedTabChanged.emit();
} else if (tab.disabled) {
} else if (import.meta.env.DEV && tab.disabled) {
console.warn('You cannot activate a disabled tab');
}
},
Expand All @@ -318,9 +318,11 @@ export class SbbTabGroupElement extends LitElement {
} else {
tab.insertAdjacentHTML('afterend', '<div>No content.</div>');
tab.relatedContent = tab.nextElementSibling as HTMLElement;
console.warn(
`Missing content: you should provide a related content for the tab ${tab.outerHTML}.`,
);
if (import.meta.env.DEV) {
console.warn(
`Missing content: you should provide a related content for the tab ${tab.outerHTML}.`,
);
}
}
tab.tabIndex = -1;
tab.disabled = isValidAttribute(tab, 'disabled');
Expand Down
6 changes: 3 additions & 3 deletions src/components/tag/tag-group/tag-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ export class SbbTagGroupElement extends SbbNamedSlotListMixin<SbbTagElement, typ
const valueAsArray = Array.isArray(value) ? value : [value];
tags.forEach((t) => (t.checked = valueAsArray.includes(t.value ?? t.getAttribute('value'))));
} else {
if (Array.isArray(value)) {
if (!Array.isArray(value)) {
tags.forEach((t) => (t.checked = (t.value ?? t.getAttribute('value')) === value));
} else if (import.meta.env.DEV) {
console.warn('value must not be set as an array in singular mode.', value);
return;
}
tags.forEach((t) => (t.checked = (t.value ?? t.getAttribute('value')) === value));
}
}
public get value(): string | string[] | null {
Expand Down
4 changes: 3 additions & 1 deletion src/components/toggle/toggle/toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ export class SbbToggleElement extends LitElement {
options[0];

if (!selectedOption) {
isBrowser() && console.warn(`sbb-toggle: No available options! (${this.id || 'No id'})`);
if (import.meta.env.DEV && isBrowser()) {
console.warn(`sbb-toggle: No available options! (${this.id || 'No id'})`);
}
return;
}
if (!selectedOption.checked) {
Expand Down
12 changes: 8 additions & 4 deletions src/components/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { defineConfig, mergeConfig, type UserConfig } from 'vite';

import {
copyAssets,
copySass,
customElementsManifest,
distDir,
dts,
Expand All @@ -28,9 +29,9 @@ export default defineConfig((config) =>
mergeConfig(rootConfig, <UserConfig>{
root: packageRoot.pathname,
plugins: [
...(config.command === 'build' ? [dts()] : []),
...(isProdBuild(config)
? [
dts(),
customElementsManifest(),
packageJsonTemplate({
exports: {
Expand All @@ -40,7 +41,8 @@ export default defineConfig((config) =>
},
},
}),
copyAssets(['_index.scss', 'core/styles/**/*.scss', '../../README.md']),
copyAssets(['_index.scss', '../../README.md']),
copySass('core/styles'),
typography(),
]
: []),
Expand All @@ -51,9 +53,11 @@ export default defineConfig((config) =>
entry: entryPoints,
formats: ['es'],
},
minify: false,
outDir: new URL('./components/', distDir).pathname,
minify: isProdBuild(config),
outDir: new URL(`./components/${isProdBuild(config) ? '' : 'development/'}`, distDir)
.pathname,
emptyOutDir: true,
sourcemap: isProdBuild(config) ? false : 'inline',
rollupOptions: {
external: (source: string, importer: string | undefined) => {
if (
Expand Down
2 changes: 1 addition & 1 deletion src/react/core/create-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
import type React from 'react';

const NODE_MODE = isServer;
const DEV_MODE = true;
const DEV_MODE = import.meta.env.DEV;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type DistributiveOmit<T, K extends string | number | symbol> = T extends any
Expand Down
7 changes: 4 additions & 3 deletions src/react/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@ export default defineConfig((config) =>
root: new URL('.', import.meta.url).pathname,
plugins: [
generateReactWrappers(),
...(isProdBuild(config) ? [dts(), packageJsonTemplate()] : []),
...(config.command === 'build' ? [dts()] : []),
...(isProdBuild(config) ? [packageJsonTemplate()] : []),
],
build: {
lib: {
formats: ['es'],
},
minify: false,
outDir: new URL('./react/', distDir).pathname,
minify: isProdBuild(config),
outDir: new URL(`./react/${isProdBuild(config) ? '' : 'development/'}`, distDir).pathname,
emptyOutDir: true,
rollupOptions: {
external: [/^@sbb-esta\/lyne-components\/?/, /^@lit\/react\/?/, /^lit\/?/, /^react/],
Expand Down
40 changes: 40 additions & 0 deletions tools/vite/copy-sass.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { readFileSync } from 'fs';
import { dirname, join, relative } from 'path';

import * as glob from 'glob';
import type { PluginOption, ResolvedConfig } from 'vite';

import { root } from './build-meta';

export function copySass(sassRoot: string): PluginOption {
let viteConfig: ResolvedConfig;
return {
name: 'package-json-templating',
configResolved(config) {
viteConfig = config;
},
generateBundle() {
if (viteConfig.command !== 'build') {
return;
}
for (const file of glob.sync(`${sassRoot}/**/*.scss`, { cwd: viteConfig.root })) {
this.emitFile({
type: 'asset',
fileName: file,
source: readFileSync(join(viteConfig.root, file), 'utf8').replace(
/@use '(node_modules\/[^']+)'/g,
(_m, useFile: string) => {
const outFile = join(sassRoot, useFile.replaceAll('/', '_'));
this.emitFile({
type: 'asset',
fileName: outFile,
source: readFileSync(new URL(useFile, root), 'utf8'),
});
return `@use '${relative(dirname(file), outFile)}'`;
},
),
});
}
},
};
}
1 change: 1 addition & 0 deletions tools/vite/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './build-meta';
export * from './copy-assets';
export * from './copy-sass';
export * from './custom-elements-manifest';
export * from './dts';
export * from './generate-react-wrappers';
Expand Down
4 changes: 2 additions & 2 deletions tools/vite/package-json-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ export function packageJsonTemplate(
(current, next) =>
Object.assign(current, {
[`./${next[0].replace(/\/index$/, '')}`]: {
types: `./${next[0]}.d.ts`,
import: `./${next[0]}.js`,
types: `./development/${next[0]}.d.ts`,
development: `./development/${next[0]}.js`,
default: `./${next[0]}.js`,
},
}),
Expand Down

0 comments on commit 909b2e0

Please sign in to comment.