Journals for

2023-03-07

🔗

Today I encountered an issue using Vite with the Rush monorepo software. Rush keeps its lockfile in an unusual place, and so Vite could not automatically check the lockfile to know when to clear its cache. But it turns out to be pretty easy to code your own logic here.

// vite.config.js
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const dirname = path.dirname(fileURLToPath(import.meta.url));

function lockfileNeedsRebuild() {
  const lockFilePath = path.resolve(
    dirname,
    '../../common/config/rush/pnpm-lock.yaml'
  );
  const lockFileDatePath = path.resolve(dirname, '.last-lockfile-date');

  let lockFileSavedDate = '';
  try {
    lockFileSavedDate = fs.readFileSync(lockFileDatePath).toString();
  } catch (e) {
    // It's fine if there is no existing file.
  }

  const lockFileDate = fs.statSync(lockFilePath).mtime.valueOf().toString();

  if (lockFileSavedDate.trim() !== lockFileDate) {
    fs.writeFileSync(lockFileDatePath, lockFileDate);
    return true;
  }

  return false;
}

/** @type {import('vite').UserConfig} */
const config = {
  optimizeDeps: {
    force: lockfileNeedsRebuild(),
  },
  // ... and other config
};
export default config;


Thanks for reading! If you have any questions or comments, please send me a note on Twitter.