|
| 1 | +/* |
| 2 | + Inserts a <base href="..."> tag into storybook-static/index.html when STORYBOOK_BASE_HREF env var is set. |
| 3 | + This avoids changing dev server behavior and only affects built files. |
| 4 | +
|
| 5 | + Usage: set env var STORYBOOK_BASE_HREF (e.g. /pro-react-admin/storybook/) then run build-storybook. |
| 6 | +*/ |
| 7 | +const fs = require('fs') |
| 8 | +const path = require('path') |
| 9 | + |
| 10 | +const outDir = path.resolve(process.cwd(), 'storybook-static') |
| 11 | +const indexPath = path.join(outDir, 'index.html') |
| 12 | + |
| 13 | +const baseHref = process.env.STORYBOOK_BASE_HREF |
| 14 | + |
| 15 | +// Only accept a web-style base (starting with / or http), to avoid inserting local filesystem paths |
| 16 | +if (!baseHref || !(baseHref.startsWith('/') || baseHref.startsWith('http'))) { |
| 17 | + console.log('No STORYBOOK_BASE_HREF provided, skipping base href insertion.') |
| 18 | + process.exit(0) |
| 19 | +} |
| 20 | + |
| 21 | +if (!fs.existsSync(indexPath)) { |
| 22 | + console.error(`Cannot find ${indexPath}. Did you run build-storybook?`) |
| 23 | + process.exit(1) |
| 24 | +} |
| 25 | + |
| 26 | +let html = fs.readFileSync(indexPath, 'utf8') |
| 27 | + |
| 28 | +if (html.includes(`<base href="${baseHref}">`)) { |
| 29 | + console.log('Base href already inserted.') |
| 30 | + process.exit(0) |
| 31 | +} |
| 32 | + |
| 33 | +// Insert <base> just after opening <head> |
| 34 | +const replaced = html.replace(/<head(.*?)>/i, (m) => { |
| 35 | + return m + `\n <base href="${baseHref}">` |
| 36 | +}) |
| 37 | + |
| 38 | +fs.writeFileSync(indexPath, replaced, 'utf8') |
| 39 | +console.log(`Inserted <base href="${baseHref}"> into ${indexPath}`) |
| 40 | +process.exit(0) |
0 commit comments