原因在使用storybook@6.1.21时,你可能只想专注于一个或多个UI组件,但storybook将所有组件都打包了;由此产生的问题显示了太多的组件;启动时间慢;如果其他包有问题,会导致启动失败;需求启动时,只会启动指定的UI组件,其他组件不会被打包渲染;配置文件1.文件目录2.config.jsimport{configure}from'@storybook/react';constreq=require.context('../packages',true,/\.(stories|story)\.(tsx|jsx|js)$/);functionloadStories(){req.keys().forEach(filename=>req(filename));}configure(loadStories,module);3。webpack.config.jsmodule.exports=({config})=>{/**其他配置**/returnconfig;};4.版本信息storybook:6.1.21解决方案:方案一:webpack.DefinePlugin原理使用webpack.DefinePlugin定义全局变量,将config.js中的requirecontext路径替换掉config.jsimport{configure}from'@storybook/react';/**变化点:用占位符字符串REPLACE_COMPONENT_DIR_REG_STR替换真实路径**/constreq=require.context('../packages',true,REPLACE_COMPONENT_DIR_REG_STR);/**end**/functionloadStories(){req.keys().forEach(filename=>req(filename));}configure(loadStories,module);webpack.config.jsconstwebpack=require('webpack');/**变化点:从命令行参数中获取组件名称**/letcomponentName;try{const[cmd1,cmd2]=JSON.parse(process.env.npm_config_argv).original.slice(-2);if(cmd1==='start'&&cmd2&&cmd2.trim()){componentName=cmd2.split(',').map(item=>item&&item.trim()).filter(Boolean).join('|');}}catch(e){console.error(e)}/**end**/module.exports=({config})=>{/**其他配置**//**VariesPoint:使用webpack.DefinePlugin插件打包时替换占位符字符串**/config.plugins.push(newwebpack.DefinePlugin({REPLACE_COMPONENT_DIR_REG_STR:`/\\/(${componentName})\\/.*\\.(stories|story)\\.(tsx|jsx|js)$/`}));/**结束**/返回配置;};方案二:自定义加载器原理自定义一个webpack加载器,在打包config.js文件时替换require.context的正则表达式config.jsimport{configure}from'@storybook/react';/**改变点:使用占位符正则表达式中的字符串%REPLACE_COMPONENT_DIR_NAME%**/constreq=require.context('../packages',true,/%REPLACE_COMPONENT_DIR_NAME%\.(stories|story)\.(tsx|jsx|js)$/);/**end**/functionloadStories(){req.keys().forEach(filename=>req(filename));}configure(loadStories,module);webpack.config.js/**变化Point**/constpath=require('path');/**end**/module.exports=({config})=>{/**otherconfig**//**改变点:for.storybook/config.js文件自定义加载器**/config.module.rules.push({test:/\.storybook\/config\.js$/,use:path.resolve(__dirname,'./cus-set-package-loader.js'),});/**end**/returnconfig;};.storybook/cus-set-package-loader.jsmodule.exports=res=>{//从命令行参数中获取组件名letcomponentNametry{const[cmd1,cmd2]=JSON.parse(process.env.npm_config_argv).original.slice(-2)if(cmd1==='start'&&cmd2&&cmd2.trim())componentName=cmd2}catch(e){console.error(e)}console.log('\n\x1b[33m%s\x1b[0m',`packagenames:${componentName||'allpackages'}`)//处理多个组件和组件名称中的空格constcomponentDirName=componentName?`\\/(${componentName.split(',').map(item=>item&&item.trim()).filter(Boolean).join('|')})\\/.*`:''//替换配置文件中的占位符returnres.replace('%REPLACE_COMPONENT_DIR_NAME%',componentDirName)}开始npmstartcomponentName1,componentName2
