如何在故事书中配置Webpack以允许babel导入React组件到项目文件夹之外

时间:2019-06-13 00:33:26

标签: reactjs webpack babeljs jsx storybook

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

所以不是这样的结构

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来解析components文件夹


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

2 个答案:

答案 0 :(得分:3)

我是通过如下编辑.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;
  }
};

答案 1 :(得分:0)

使用此命令:https://storybook.js.org/docs/configurations/custom-webpack-config/#debug-the-default-webpack-config

调试最终的webpack配置。您可能必须更改babel-loader的include和exclude。

默认情况下,它里面有include: [ './' ],我认为删除它应该可以使它工作。