【问题标题】:Using a packaged linked via npm link in create-react-app leads to webpack error: module has no exports在 create-react-app 中使用通过 npm 链接链接的打包链接会导致 webpack 错误:模块没有导出
【发布时间】:2022-11-12 11:33:09
【问题描述】:

我正在本地开发一个 React 挂钩,并尝试在相邻的 create-react-app 项目(文件夹 example/ 下)中对其进行测试。但是,导入所述链接模块会导致以下错误:

Attempted import error: 'usePleaseStay' is not exported from 'react-use-please-stay' (imported as 'usePleaseStay').
ERROR in ./src/App.tsx 10:2-15
export 'usePleaseStay' (imported as 'usePleaseStay') was not found in 'react-use-please-stay' (module has no exports)

ERROR in ./src/App.tsx 14:10-23
export 'usePleaseStay' (imported as 'usePleaseStay') was not found in 'react-use-please-stay' (module has no exports)

我的 App.tsx:

import React from 'react';
import { usePleaseStay } from 'react-use-please-stay';

function App() {
  usePleaseStay(["Title One!", "Title Two!", "Title Three?!?"]);
  return (
    <></>
  );
}

export default App;

当我 cmd+单击react-use-please-stay 时,我得到的文件:

export { usePleaseStay } from './hooks/usePleaseStay';

正如预期的那样,我的钩子源代码中的dist/index.d.ts 文件是正确的。显然,那里有出口!

npm ls --location=global --depth=0 --link=true 的输出:

react-use-please-stay@1.0.0 -> ./../../../../../projects/react-use-please-stay

这里到底发生了什么?这是 create-react-app 混淆了我们太多的 webpack 决策的经典问题吗?

非常感谢任何帮助。

【问题讨论】:

    标签: reactjs typescript webpack npm-link


    【解决方案1】:

    啊,想通了。只是一个班轮。我正在将我的模块打包到 Common JS。这与 create-react-app 的 Webpack 配置不能很好地配合。我通过更改我的 rollup.config.js 来解决这个问题:

    import typescript from '@rollup/plugin-typescript';
    import pkg from './package.json' assert { type: "json" };
    
    export default {
      input: 'src/index.ts',
      output: {
        file: pkg.main,
        format: 'cjs',
        sourcemap: true,
        strict: false,
      },
      plugins: [typescript()],
      external: ['react']
    };
    

    至:

    import typescript from '@rollup/plugin-typescript';
    import pkg from './package.json' assert { type: "json" };
    
    export default {
      input: 'src/index.ts',
      output: {
        file: pkg.main,
        format: 'module',
        sourcemap: true,
        strict: false,
      },
      plugins: [typescript()],
      external: ['react']
    };
    

    只需将 format: 'cjs' 更改为 format: 'module'

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多