Skip to content

Instantly share code, notes, and snippets.

@dlupu
Created January 24, 2021 21:17
Show Gist options
  • Save dlupu/b0c9e19b8eace962083c613ff705434e to your computer and use it in GitHub Desktop.
Save dlupu/b0c9e19b8eace962083c613ff705434e to your computer and use it in GitHub Desktop.
Storybook configuration that picks up Ruby on Rails webpacker packs
// .storybook/main.js
//
// this module makes the assumption that
// the local host is accessible at http://localhost:3001"
let fs = require('fs');
module.exports = {
stories: ['../spec/components/**/*.stories.json'],
addons: [
'@storybook/addon-controls',
],
webpackFinal: async (config) => {
config = injectRailsPacks(config)
return config;
},
};
const injectRailsPacks = (config) => {
// change HtmlWebpackPlugin
// * to inject assets from manifest
// by overriding the files that need to be inserted into the preview header
// https://github.com/storybookjs/storybook/blob/v6.1.15/lib/core/src/server/preview/iframe-webpack.config.ts#L125
// * disable cache, hence forcing the preview template to be regenerated on every build
let configPluginOptions = config.plugins[1].options;
let originalTemplateParametersFunction = configPluginOptions.templateParameters;
config.plugins[1].options = {
...configPluginOptions,
cache: false,
templateParameters: (compilation, files, options) => {
let railsPacks = getRailsPacks();
files.js = files.js.concat(railsPacks.js)
files.css = files.css.concat(railsPacks.css)
// console.log('===================')
// console.log('js:', files.js)
// console.log('css:', files.css)
// console.log('===================')
return originalTemplateParametersFunction(compilation, files, options)
}
}
return config;
}
const getRailsPacks = () => {
// TODO: change this to list your packs
let packs = ['application'];
let manifestPath = __dirname + '/../public/packs/manifest.json'
let json = JSON.parse(fs.readFileSync(manifestPath).toString());
let js_files = [];
let css_files = [];
packs.forEach((pack) => {
json?.entrypoints?.[pack]?.js?.forEach((js_path) => {
js_files.push("http://localhost:3001" + js_path)
})
json?.entrypoints?.[pack]?.css?.forEach((css_path) => {
css_files.push("http://localhost:3001" + css_path)
})
})
// console.log("------------====---------")
// console.log('manifest', json)
// console.log("js_files", js_files)
// console.log("css_files", css_files)
// console.log("------------====---------")
return ({
js: js_files,
css: css_files
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment