reactjs - 如何在故事书中配置 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 链接
解决方案
我通过.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;
}
};
推荐阅读
- r - 在 R 中的箱形图旁边绘制垂直正态分布
- regex - 从 JMETER JSONPath 值中提取最后六位数字
- ruby-on-rails - 模型类的 Searchkick 聚合
- kubernetes - Kubernetes pod 因卷附加问题而失败
- python - 将 softmax 层添加到 LSTM 网络“冻结”输出
- javascript - 更改变量名称的 For 循环
- python - Flask 表单数据为空
- java - 如何解决 Android Studio 中的 Phenotype API 错误?
- r - 按组更改 siberDensityPlot 颜色
- python - 在 AWS Lambda 上运行 python 脚本时出错