Skip to content

Commit

Permalink
Refactor main.js with separating build step
Browse files Browse the repository at this point in the history
  • Loading branch information
sanak committed Nov 18, 2024
1 parent dedc1b2 commit a7c4693
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 131 deletions.
6 changes: 4 additions & 2 deletions .github/workflows/deploy-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ jobs:

- name: Build Storybook
env:
BASE_URL: "/${{ github.event.repository.name }}/"
run: npm run build-storybook
BASE_PATH: "/${{ github.event.repository.name }}/"
run: |
npm run build-storybook
node scripts/update-assets-paths.js storybook-static ${BASE_PATH}
- uses: actions/upload-pages-artifact@v3
with:
Expand Down
73 changes: 3 additions & 70 deletions .storybook/main.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,9 @@
import path from 'path';
import fs from 'fs';
import vitePluginHtml from '../src/utils/vite-plugin-html';

const framework = process.env.BUILDER == 'vite' ? '@storybook/html-vite'
: '@storybook/html-webpack5'

// Add escaping process with reference to vite-plugin-raw(https://github.com/xingw-z/vite-plugin-raw)
function vitePluginHtml() {
return {
name: 'vite-plugin-html',
apply: 'serve',
async transform (_, id) {
const files = [/\.html$/];
if (files.find((v) => v.test(id))) {
const buf = fs.readFileSync(id, 'utf-8');
return {
code: `export default ${JSON.stringify(buf)}`
};
} else {
return {};
}
}
}
}

// Add escaping process with reference at build time (https://github.com/vitejs/vite/discussions/12788#discussioncomment-5557866)
function vitePluginHtmlForBuild() {
const postfix = '?html-import';
const postfixRegExp = /\?html-import$/;
return {
name: 'vite-plugin-html-for-build',
enforce: 'pre',
apply: 'build',
async resolveId (id, importer, options) {
if (/\.html$/.test(id) && !options.isEntry) {
const res = await this.resolve(id, importer, {
skipSelf: true,
...options
});
if (!res || res.external) {
return res;
}
return res.id + postfix;
}
},
async load(id) {
if (!id.endsWith(postfix)) {
return;
}
let buf = fs.readFileSync(id.replace(postfixRegExp, ''), 'utf-8');
if (process.env.BASE_URL) {
buf = buf.replace(/"\/(attachments|images|javascripts)\//g, `"${process.env.BASE_URL}$1/`);
}
return `export default ${JSON.stringify(buf)}`;
}
}
}

export default {
stories: [
"../src/stories"
Expand Down Expand Up @@ -88,20 +36,6 @@ export default {
sources: false,
}
}
// Replace absolute paths for GitHub Pages
if (process.env.BASE_URL) {
config.module.rules.push({
test: /.html$/,
loader: 'string-replace-loader',
options: {
search: '"\/(attachments|images|javascripts)\/',
replace(match, p1, offset, string) {
return `"${process.env.BASE_URL}${p1}/`;
},
flags: 'g'
},
});
}
return {
...config,
resolve: {
Expand All @@ -119,8 +53,7 @@ export default {
viteFinal: async (config) => {

config.plugins.push(
vitePluginHtml(),
vitePluginHtmlForBuild()
vitePluginHtml()
)

return {
Expand All @@ -133,7 +66,7 @@ export default {
define: {
"process.env": {}
},
base: process.env.BASE_URL || '/'
base: process.env.BASE_PATH || '/'
}
}
}
58 changes: 0 additions & 58 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"storybook": "^8.4.2"
},
"devDependencies": {
"string-replace-loader": "^3.1.0",
"vite": "^5.4.10"
},
"files": [
Expand Down
46 changes: 46 additions & 0 deletions scripts/update-assets-paths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const fs = require('fs');
const path = require('path');

// Get command-line arguments
const args = process.argv.slice(2);
const targetDir = args[0]; // First argument: target directory
const basePath = args[1]; // Second argument: base path for assets with leading/trailing slashes

// Check if required arguments are provided
if (!targetDir || !basePath) {
console.error('Usage: node update-assets-paths.js <target directory> <base path>');
process.exit(1);
}

function updateAssetsPaths(targetDir, basePath) {
const files = fs.readdirSync(targetDir);

files.forEach((file) => {
const filePath = path.join(targetDir, file);
const stat = fs.statSync(filePath);

if (stat.isDirectory()) {
updateAssetsPaths(filePath, basePath); // Recursively process subdirectories
} else if (file.endsWith('.html') || file.endsWith('.css') || file.endsWith('.js')) {
let content = fs.readFileSync(filePath, 'utf8');

if (content.match(/(["'\(])\/(assets|attachments|images|javascripts|stylesheets)\//g)) {
// Add base path to assets paths
const updatedContent = content.replace(
/(["'\(])\/(assets|attachments|images|javascripts|stylesheets)\//g,
`$1${basePath}$2/`
);

fs.writeFileSync(filePath, updatedContent, 'utf8');
console.log(`Updated: ${filePath}`);
}
}
});
}

try {
updateAssetsPaths(targetDir, basePath);
console.log('Processing completed successfully.');
} catch (error) {
console.error('Error during processing:', error);
}
57 changes: 57 additions & 0 deletions src/utils/vite-plugin-html.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import fs from 'fs';

// Add escaping process with reference to vite-plugin-raw(https://github.com/xingw-z/vite-plugin-raw)
function vitePluginHtmlForServe() {
return {
name: 'vite-plugin-html-for-server',
apply: 'serve',
async transform (_, id) {
const files = [/\.html$/];
if (files.find((v) => v.test(id))) {
const buf = fs.readFileSync(id, 'utf-8');
return {
code: `export default ${JSON.stringify(buf)}`
};
} else {
return {};
}
}
}
}

// Add escaping process with reference at build time (https://github.com/vitejs/vite/discussions/12788#discussioncomment-5557866)
function vitePluginHtmlForBuild() {
const postfix = '?html-import';
const postfixRegExp = /\?html-import$/;
return {
name: 'vite-plugin-html-for-build',
enforce: 'pre',
apply: 'build',
async resolveId (id, importer, options) {
if (/\.html$/.test(id) && !options.isEntry) {
const res = await this.resolve(id, importer, {
skipSelf: true,
...options
});
if (!res || res.external) {
return res;
}
return res.id + postfix;
}
},
async load(id) {
if (!id.endsWith(postfix)) {
return;
}
const buf = fs.readFileSync(id.replace(postfixRegExp, ''), 'utf-8');
return `export default ${JSON.stringify(buf)}`;
}
}
}

export default function vitePluginHtml() {
return [
vitePluginHtmlForServe(),
vitePluginHtmlForBuild()
]
}

0 comments on commit a7c4693

Please sign in to comment.