无法使用我的自定义反应库对项目进行单元测试

问题描述 投票:0回答:1

我创建了这个 NPM 包 https://www.npmjs.com/package/@applaudo/react-clapp-ui

我可以使用创建反应应用程序在其他项目中安装它并正确使用它,并且工作正常,但是当我尝试在目标项目中运行单元测试时,我从笑话中收到此错误

 FAIL  src/components/test.test.tsx
  ● Test suite failed to run

    Cannot find module '@applaudo/react-clapp-ui' from 'src/components/test1.tsx'

    Require stack:
      src/components/test1.tsx
      src/components/test.test.tsx

      1 | import Mx from 'rc-picker/lib/locale/es_MX';
    > 2 | import { Button, Content, DatePicker, Heading, Label, useClapp } from "@applaudo/react-clapp-ui";
        | ^
      3 |
      4 |
      5 | export const Test1 = () => {

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
      at Object.<anonymous> (src/components/test1.tsx:2:1)

这是我的 rollup.config

import commonjs from '@rollup/plugin-commonjs';
import dts from 'rollup-plugin-dts';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';
import postcss from 'rollup-plugin-postcss';
import { RollupOptions } from 'rollup';
import { terser } from 'rollup-plugin-terser';
import typescript from '@rollup/plugin-typescript';

const dependencies = Object.keys(pkg.dependencies);
const external = [...dependencies, 'lodash', /\.css$/, /rc-util*/];

const options: RollupOptions[] = [
  {
    input: 'index.tsx',
    output: {
      name: pkg.name,
      dir: 'dist',
      format: 'es',
      sourcemap: false,
      preserveModules: true,
      exports: 'named',
      assetFileNames: '[name][extname]',
    },
    plugins: [
      // @ts-ignore
      peerDepsExternal(),
      commonjs(),
      typescript({ tsconfig: './tsconfig.json' }),
      postcss({
        minimize: true,
        extract: true,
        exec: true,
        sourceMap: true,
        use: ['sass'],
      }),
      terser(),
    ],
    external,
  },
  {
    input: 'dist/dts/index.d.ts',
    output: {
      file: 'dist/index.d.ts',
      format: 'commonjs',
    },
    external: [/\.scss$/, /\.css$/],
    plugins: [
      dts({
        compilerOptions: {
          baseUrl: 'dist/dts',
        },
      }),
    ],
  },
];

export default options;

这是 package.json 的片段

{
  "license": "Apache-2.0",
  "module": "dist/index.js",
  "typings": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "sideEffects": [
    "*.scss"
  ]
}

我尝试使用formar commonjs来打包lib而不是es,但在我使用react测试库或酶测试了jest和TS的3个项目中仍然不起作用,同样的错误。

所以我不确定如何打包该库,以便它可以与 jest 和 webpack 一起使用(目前与 webpack 一起使用)

typescript npm shared-libraries rollup
1个回答
0
投票

事实证明,jest 仅支持您正在处理的项目的 ES 模块导出,除非在 jest 配置中明确指定,否则来自 node_modules 的任何内容都不会转译或转换为 CJS。

简单的解决方案是在 package.json 中添加一个 main 字段,指向一个将模块导出为 CJS 的文件,这就是 jest 可以使用的,并且还具有 ES 导出的模块字段,以便 webpack 仍然可以使用 treeshaking 和编译时导入等..

{
  "module": "dist/index.js",
  "main": "lib/index.js",
  "typings": "dist/index.d.ts",
  "files": [
    "dist",
    "lib"
  ],
}

然后在汇总配置中添加额外的输出以生成相同的内容,但采用 CJS 格式。

© www.soinside.com 2019 - 2024. All rights reserved.