gpt4 book ai didi

reactjs - 如何在storybook中配置webpack以允许babel导入项目文件夹之外的react组件

转载 作者:行者123 更新时间:2023-12-03 13:32:04 26 4
gpt4 key购买 nike

我能够成功运行故事书并在故事书项目文件夹中开发 react 组件。但是,我试图将包含所有组件的文件夹向上移动一个级别(成为故事书文件夹的同级文件夹)。

所以不要像这样的结构

storybook
├── components
│ ├── Foo.js
│ └── Bar.js
├── stories
│ ├── index.stories.js

我有这样的文件夹结构

my_example_project
├── my_components
│ ├── Foo.js
│ └── Bar.js
├── my_storybook
│ ├── ...

但是,当我尝试将组件导入故事时,出现以下错误

ERROR in ../my_components/Bar.js 4:9
Module parse failed: Unexpected token (4:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| const Bar = () => {
> return <div>I am a Bar</div>;
| };

我尝试通过将 webpack.config.js 文件添加到我的 Storybooks .storybook 文件夹中来配置我的 webpack 来解析组件文件夹,如下所示


const path = require('path');

// Export a function. Accept the base config as the only param.
module.exports = async ({ config, mode }) => {
// Make whatever fine-grained changes you need

config.module.rules.push({
test: /\.(js|jsx)$/,
exclude: [/bower_components/, /node_modules/, /styles/],
loader: 'babel-loader',
include: path.resolve(__dirname, '../my_components/*'),
query: {
presets: ['@babel/preset-react']
}
});


// Return the altered config
return config;
};

但是,我遇到了同样的错误。我做错了什么?

这是一个github link完整示例项目的示例

最佳答案

我通过编辑 .storybook/main.js 来完成此操作,如下所示:

const webpack = require('webpack');
const path = require('path');

module.exports = {
stories: [
'../src/**/*.stories.js',
'../../../packages/react-components/src/**/*.stories.js'
],
addons: [
'@storybook/addon-docs',
'@storybook/addon-viewport'
],

webpackFinal: async (config) => {
// Ensure shared component stories are transpiled.
config.module.rules[0].include.push(
path.resolve('../../packages/react-components/src')
);

return config;
}
};

关于reactjs - 如何在storybook中配置webpack以允许babel导入项目文件夹之外的react组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56571943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com