首页 > 解决方案 > 如何在故事书中配置 webpack 以允许 babel 在项目文件夹之外导入反应组件

问题描述

我能够成功运行故事书并在故事书项目文件夹中开发反应组件。但是,我正在尝试将包含我所有组件的文件夹上移一个级别(成为故事书文件夹的兄弟)。

所以,而不是像这样的结构

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>;
| };

我尝试通过向我的故事书 .storybook 文件夹添加一个webpack.config.js文件来配置我的 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 链接

标签: reactjswebpackbabeljsjsxstorybook

解决方案


我通过.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;
  }
};

推荐阅读