Skip to content

Commit

Permalink
🔨 [#724] Set up npm package build with Vite
Browse files Browse the repository at this point in the history
Slowly preparing to swap over the ESM build for the NPM package from
CRA/webpack to Vite.

This configuration was hand-crafted. Initially the library build config
was used/attempted (see
https://v5.vite.dev/config/build-options.html#build-lib), but this
proved not to be acceptable since it would inline all the font
assets, which blows up the CSS file size to unacceptable sizes.

This is very inefficient, since all the font assets would be loaded,
even if the browser only requires one type (woff2 vs ttf etc.). It
was also inlining the leaflet static images.

Using vitejs/vite#3295 (comment)
as a reference (which crucially doesn't define build.lib) allows us to
configure the underlying rollup setup without inlining assets.
  • Loading branch information
sergei-maertens committed Dec 30, 2024
1 parent e473e32 commit d5b0382
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
/storybook-static
/build
/dist
/dist-vite
/lib
/esm
*.tgz
Expand Down
41 changes: 41 additions & 0 deletions vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,22 @@ import {defineConfig} from 'vite';
import jsconfigPaths from 'vite-jsconfig-paths';
import {coverageConfigDefaults} from 'vitest/config';

import {dependencies, peerDependencies} from './package.json';

const externalPackages = [
...Object.keys(dependencies || {}),
...Object.keys(peerDependencies || {}),
'formiojs',
'lodash',
'@formio/vanilla-text-mask',
'@babel/runtime',
'@utrecht/component-library-react',
];

// Creating regexes of the packages to make sure subpaths of the
// packages are also treated as external
const regexesOfPackages = externalPackages.map(packageName => new RegExp(`^${packageName}(/.*)?`));

// inspired on https://dev.to/koistya/using-ejs-with-vite-48id and
// https://github.com/difelice/ejs-loader/blob/master/index.js
const ejsPlugin = () => ({
Expand Down Expand Up @@ -54,6 +70,31 @@ export default defineConfig({
cjsTokens(),
ejsPlugin(),
],
build: {
target: 'modules', // the default
outDir: 'dist-vite',
assetsInlineLimit: 8 * 1024, // 8 KiB
cssCodeSplit: false,
rollupOptions: {
input: 'src/sdk.jsx',
external: regexesOfPackages,
output: {
dir: 'dist-vite/esm',
format: 'esm',
preserveModules: true,
preserveModulesRoot: 'src',
entryFileNames: '[name].js',
assetFileNames: ({name}) => {
if (name?.endsWith('.css')) {
return '[name].[ext]';
}
return 'static/media/[name].[hash:8].[ext]';
},
sourcemap: false,
},
preserveEntrySignatures: 'strict',
},
},
css: {
preprocessorOptions: {
scss: {
Expand Down

0 comments on commit d5b0382

Please sign in to comment.