jest 文件转换,适用于 esm 模块或 commonjs

问题描述

我有一个测试工具包,其中一个是 jest 文件转换器:

import path from 'path';

export const process = (src: string,filename: string): string => {
  return `module.exports = ${JSON.stringify(path.basename(filename))};`;
};

然后在 jest.config.ts

中设置
  transform: {
    // rest
    '^.+\\.csv$': path.join(__dirname,'./fileTransform.js'),

我正在尝试将包升级为 esm 模块,并且我希望转换在被 esm 或 commonjs 模块使用时工作,我尝试将代码重写为:

import path from 'path';

const createExport = (filename: string) =>
  `
    if (typeof module === 'object' && module) {
        Object.defineProperty(exports,"__esModule",{
          value: true
      });
        module.exports = ${JSON.stringify(path.basename(filename))}
    } else {
      Object.defineProperty(exports,{
          value: true
      });
      exports.default = ${JSON.stringify(path.basename(filename))};
    }
`
    .trim()
    .replace(/^\s{4}/g,'');

export const process = (src: string,filename: string): string => {
  const exp = createExport(filename);

  return exp;
};

但我收到此错误

TypeError:Jest:转换必须导出某些内容

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)