reactjs 如何使用storybook动态导入自定义包?

m1m5dgzv  于 2023-04-11  发布在  React
关注(0)|答案(1)|浏览(220)

所以我有一个自定义的private npm包,我想动态导入它,就像这样。

export default function SelectedIcon({path, ...props}: Props) {
  const {data: icon} = require(`@mypackagelib/icons/${path}`)
  return <Icon icon={icon} {...props} />
}
// I also tried to have it differently such as: 
export default function SelectedIcon({path, ...props}: Props) {
  const Component = React.lazy(() => import(`@mypackagelib/icons/${path}`))
  return <Component {...props} />
}
// However, same error, so it seems like dynamically importing this is the problem

但是,我得到了许多错误,在运行Storybook时,库中不同组件的所有相同消息

Module parse failed: Unexpected token (2:101)
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
| /// <reference types="react" />
| import { PropA, PropB } from '../../File';
> declare function NameOfAComponent(props: PropA): JSX.Element;
| declare namespace NameOfAComponent {
|     var data: PropB;

奇怪的是,我不明白的是,如果我像下面的代码一样导入包,那么它就可以工作了

import OneOfTheComponent from '@mypackagelib/icons/OneOfTheComponent'

但是,我有一个案例,我需要使用动态导入
我用tscts-node构建**@mypackagelib**包时,配置tsconfig.json如下

{
  "compilerOptions": {
    "outDir": "dist",
    "target": "ES2020",
    "module": "commonjs",
    "jsx": "react",
    "lib": ["es6", "dom", "ES2020"],
    "moduleResolution": "node",
    "declaration": true,
    "strict": true,
    "skipLibCheck": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": false,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmitHelpers": true,
    "importHelpers": true,
    "pretty": false,
  },
  "ts-node": {
    "swc": true
  },
  "exclude": [
    "node_moduls_local",
    "node_modules",
    "dist"
  ],
  "include": [
    "types.d.ts",
    "src/icons/**/*"
  ]
}

我的main.js在./storybook文件夹下看起来像这样:

module.exports = {
  stories: [
    "../src/**/*.stories.@(ts|tsx)"
  ],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
    "@storybook/preset-create-react-app",
    {
      name: 'storybook-addon-swc', // I thought adding this will works, but it doesn't
      options: {
        enable: true,
        enableSwcLoader: true,
        enableSwcMinify: true,
      },
    },
  ],
  framework: "@storybook/react",
  core: {
    builder: 'webpack5',
  },
  experiments: {
    topLevelAwait: true,
  }
}

我想这可能是webpack的问题。我该怎么做才能让它工作?我需要添加什么加载器?我的main.js文件需要什么样子?为什么当我使用动态导入时它需要加载器,但如果它是正常导入,它就可以正常工作?

w9apscun

w9apscun1#

尝试通过向包含路径添加本地包来配置babel-loader。

相关问题