├── .nvmrc ├── .prettierrc ├── .gitignore ├── tsconfig.json ├── .github └── workflows │ └── ci.yml ├── LICENSE ├── package.json ├── README.md └── src └── index.ts /.nvmrc: -------------------------------------------------------------------------------- 1 | 16.13.1 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 2, 3 | "useTabs": false 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | 7 | # Dependency directories 8 | node_modules/ 9 | 10 | # Build products 11 | dist/ 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "esnext", 4 | "target": "es2018", 5 | "moduleResolution": "node", 6 | "esModuleInterop": true, 7 | "strict": true, 8 | "strictNullChecks": true 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | 9 | jobs: 10 | lint: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@v2 15 | - name: Setup node 16 | uses: actions/setup-node@v2 17 | with: 18 | node-version-file: ".nvmrc" 19 | cache: "npm" 20 | - name: Use npm 8 21 | run: npm install -g npm@8.5.1 22 | - name: Install dependencies 23 | run: npm ci 24 | - name: Check formatting 25 | run: npm run format:check 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022-present Ian VanSchooten 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vite-plugin-turbosnap", 3 | "version": "1.0.3", 4 | "description": "Enables the use of Chromatic Turbosnap in vite storybook projects", 5 | "keywords": [ 6 | "vite-plugin", 7 | "chromatic", 8 | "turbosnap", 9 | "storybook", 10 | "vite", 11 | "snapshot" 12 | ], 13 | "author": "Ian VanSchooten ", 14 | "license": "MIT", 15 | "homepage": "https://github.com/IanVS/vite-plugin-turbosnap#readme", 16 | "bugs": { 17 | "url": "https://github.com/IanVS/vite-plugin-turbosnap/issues" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/IanVS/vite-plugin-turbosnap.git" 22 | }, 23 | "files": [ 24 | "dist", 25 | "*.d.ts", 26 | "LICENSE" 27 | ], 28 | "exports": { 29 | ".": { 30 | "require": "./dist/index.cjs", 31 | "import": "./dist/index.mjs", 32 | "types": "./dist/index.d.ts" 33 | } 34 | }, 35 | "main": "dist/index.cjs", 36 | "module": "dist/index.mjs", 37 | "types": "dist/index.d.ts", 38 | "scripts": { 39 | "build": "rimraf dist && unbuild", 40 | "format": "prettier --write . --ignore-path .gitignore", 41 | "format:check": "prettier --check . --ignore-path .gitignore", 42 | "prepublishOnly": "npm run build" 43 | }, 44 | "devDependencies": { 45 | "@types/node": "^17.0.19", 46 | "prettier": "^2.5.1", 47 | "typescript": "^4.5.5", 48 | "unbuild": "^0.6.9", 49 | "vite": "^2.8.4" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vite-plugin-turbosnap 2 | 3 | [![NPM version](https://img.shields.io/npm/v/vite-plugin-turbosnap?color=a1b858&label=)](https://www.npmjs.com/package/vite-plugin-turbosnap) 4 | 5 | Generate a `preview-stats.json` file from your [vite storybook](https://github.com/eirslett/storybook-builder-vite) project for consumption by [chromatic cli](https://github.com/chromaui/chromatic-cli) to support [turbosnap](https://www.chromatic.com/docs/turbosnap). Turbosnap can limit the number of files that are snapshotted by Chromatic to only those which might have changed due to the files that have changed. It is also smart enough to run all of the snapshots if certain files, like storybook config, package.json, or anything imported by preview.js has changed. 6 | 7 | _This is experimental, and may not support all project and storybook configurations, yet._ 8 | 9 | Please open an issue if you experience any trouble, and be sure to include the log file that is generated from the `--diagnostics` flag of chromatic-cli, as well as the cli's output using the `--debug --trace-changed=expanded` flags. 10 | 11 | > [!NOTE] 12 | > Storybook 8 [has this plugin built-in](https://github.com/storybookjs/storybook/blob/v8.0.0/MIGRATION.md#turbosnap-vite-plugin-is-no-longer-needed) and will automatically remove it from your config. Use `--stats-json` when building Storybook to enable Turbosnap instead. 13 | 14 | ## Setup 15 | 16 | ### Prerequisites 17 | 18 | - A [Chromatic](https://www.chromatic.com/) account. 19 | - `chromatic-cli` [6.5.0](https://github.com/chromaui/chromatic-cli/blob/main/CHANGELOG.md#650---2022-02-21) or higher. 20 | - Storybook 7, or 6.5 with `@storybook/builder-vite` [0.1.22](https://github.com/storybookjs/builder-vite/releases/tag/v0.1.22) or higher. 21 | 22 | ### Install 23 | 24 | ```bash 25 | npm i --save-dev vite-plugin-turbosnap 26 | ``` 27 | 28 | ### Configuration 29 | 30 | Add this plugin to `viteFinal` in your `.storybook/main.js`: 31 | 32 | ```js 33 | // .storybook/main.js 34 | 35 | import turbosnap from "vite-plugin-turbosnap"; 36 | import { mergeConfig } from "vite"; 37 | 38 | export default { 39 | // ... your existing storybook config 40 | async viteFinal(config, { configType }) { 41 | return mergeConfig(config, { 42 | plugins: 43 | configType === "PRODUCTION" 44 | ? [ 45 | turbosnap({ 46 | // This should be the base path of your storybook. In monorepos, you may only need process.cwd(). 47 | rootDir: config.root ?? process.cwd(), 48 | }), 49 | ] 50 | : [], 51 | }); 52 | }, 53 | }; 54 | ``` 55 | 56 | ## Usage 57 | 58 | When you run `build-storybook` to create your production storybook, an additional file will be created in the output directory, named `preview-stats.json`. See the [chromatic turbosnap docs](https://www.chromatic.com/docs/turbosnap) for more information on how to configure and use turbosnap. 59 | 60 | ## How it works 61 | 62 | The turbosnap feature of Chromatic limits the snapshots that are executed to only those which can be reliably traced back to a changed file. In order to do this, it needs to have a dependency graph of the project, so that it knows when you change `button.js`, for instance, that it needs to re-run not only the `button.stories.js` file, but also any other stories which might include your custom button component. By default, it relies on the `stats` file that is output from webpack, the default storybook builder. In order to use this feature with a vite project, this plugin collects information about each module being built by vite, constructs a mapping between each file and all of the files which import it, and generates a file that mimics that created by webpack, with only the information that the chromatic cli needs to perform its checks. 63 | 64 | ## Credits 65 | 66 | Thanks to [Gert Hengeveld](https://github.com/ghengeveld) for guidance on chromatic cli changes, and to my team at [Defined Networking](https://www.defined.net) for giving me the time to build and test this on our own chromatic storybook project. 67 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { writeFile } from "fs/promises"; 2 | import path from "path"; 3 | import type { Plugin } from "vite"; 4 | 5 | /* 6 | * Reason, Module, and Stats are copied from chromatic types 7 | * https://github.com/chromaui/chromatic-cli/blob/145a5e295dde21042e96396c7e004f250d842182/bin-src/types.ts#L265-L276 8 | */ 9 | interface Reason { 10 | moduleName: string; 11 | } 12 | interface Module { 13 | id: string | number; 14 | name: string; 15 | modules?: Array>; 16 | reasons?: Reason[]; 17 | } 18 | interface Stats { 19 | modules: Module[]; 20 | } 21 | 22 | type TurbosnapPluginOptions = { 23 | /** Project root (https://vitejs.dev/config/#root) */ 24 | rootDir: string; 25 | }; 26 | 27 | /** 28 | * Strips off query params added by rollup/vite to ids, to make paths compatible for comparison with git. 29 | */ 30 | function stripQueryParams(filePath: string): string { 31 | return filePath.split("?")[0]; 32 | } 33 | 34 | /** 35 | * We only care about user code, not node_modules, vite files, or (most) virtual files. 36 | */ 37 | function isUserCode(moduleName: string) { 38 | return Boolean( 39 | moduleName && 40 | !moduleName.startsWith("vite/") && 41 | !moduleName.startsWith("\x00") && 42 | !moduleName.startsWith("\u0000") && 43 | moduleName !== "react/jsx-runtime" && 44 | !moduleName.match(/node_modules\//) 45 | ); 46 | } 47 | 48 | export default function pluginTurbosnap({ 49 | rootDir, 50 | }: TurbosnapPluginOptions): Plugin { 51 | /** 52 | * Convert an absolute path name to a path relative to the vite root, with a starting `./` 53 | */ 54 | function normalize(filename: string) { 55 | // Do not try to resolve virtual files 56 | if (filename.startsWith("/virtual:")) { 57 | return filename; 58 | } 59 | // Otherwise, we need them in the format `./path/to/file.js`. 60 | else { 61 | const relativePath = path.relative(rootDir, stripQueryParams(filename)); 62 | // This seems hacky, got to be a better way to add a `./` to the start of a path. 63 | return `./${relativePath}`; 64 | } 65 | } 66 | 67 | /** 68 | * Helper to create Reason objects out of a list of string paths 69 | */ 70 | function createReasons(importers?: readonly string[]): Reason[] { 71 | return (importers || []).map((i) => ({ moduleName: normalize(i) })); 72 | } 73 | 74 | /** 75 | * Helper function to build a `Module` given a filename and list of files that import it 76 | */ 77 | function createStatsMapModule( 78 | filename: string, 79 | importers?: readonly string[] 80 | ): Module { 81 | return { 82 | id: filename, 83 | name: filename, 84 | reasons: createReasons(importers), 85 | }; 86 | } 87 | 88 | const statsMap = new Map(); 89 | 90 | return { 91 | name: "rollup-plugin-turbosnap", 92 | // We want this to run after the vite build plugins (https://vitejs.dev/guide/api-plugin.html#plugin-ordering) 93 | enforce: "post", 94 | moduleParsed: function (mod) { 95 | if (isUserCode(mod.id)) { 96 | mod.importedIds 97 | .concat(mod.dynamicallyImportedIds) 98 | .filter((name) => isUserCode(name)) 99 | .forEach((depIdUnsafe) => { 100 | const depId = normalize(depIdUnsafe); 101 | if (statsMap.has(depId)) { 102 | const m = statsMap.get(depId); 103 | if (m) { 104 | m.reasons = (m.reasons ?? []) 105 | .concat(createReasons([mod.id])) 106 | .filter((r) => r.moduleName !== depId); 107 | statsMap.set(depId, m); 108 | } 109 | } else { 110 | statsMap.set(depId, createStatsMapModule(depId, [mod.id])); 111 | } 112 | }); 113 | } 114 | }, 115 | 116 | generateBundle: function (this, outOpts) { 117 | const stats: Stats = { modules: Array.from(statsMap.values()) }; 118 | 119 | // If we don't know where the output is going, we can't guarantee we'll put the results in the right spot. 120 | if (!outOpts.dir) { 121 | throw new Error("Vite option `build.outDir` was not configured."); 122 | } 123 | 124 | const filename = path.resolve(outOpts.dir, "preview-stats.json"); 125 | console.log(`rollup-plugin-turbosnap: writing to ${filename}`); 126 | return writeFile(filename, JSON.stringify(stats, null, 2)); 127 | }, 128 | }; 129 | } 130 | --------------------------------------------------------------------------------