From d5b0382941874a26a77e32a7960f06a6f528e910 Mon Sep 17 00:00:00 2001 From: Sergei Maertens Date: Fri, 20 Dec 2024 09:30:12 +0100 Subject: [PATCH] :hammer: [#724] Set up npm package build with Vite 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 https://github.com/vitejs/vite/issues/3295#issuecomment-1764040087 as a reference (which crucially doesn't define build.lib) allows us to configure the underlying rollup setup without inlining assets. --- .gitignore | 1 + vite.config.mts | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/.gitignore b/.gitignore index 4fc35fc1b..a2c1fb7ca 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ /storybook-static /build /dist +/dist-vite /lib /esm *.tgz diff --git a/vite.config.mts b/vite.config.mts index 1f0ba6569..7a2fe2ced 100644 --- a/vite.config.mts +++ b/vite.config.mts @@ -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 = () => ({ @@ -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: {