开玩笑:TypeError:require(...)不是一个函数

时间:2019-06-24 07:04:58

标签: javascript reactjs ecmascript-6 jestjs

该应用程序是由React与ES6编写的,因此在应用程序内部使用了importexport语句。因此,Jest配置为与ES6兼容,但是编译后的node_modules依赖项导致在测试开始时出现TypeError: require(...) is not a function的错误。我认为发生这种情况是因为jest被配置为与babel-jest一起使用来处理import语句,但是编译后的代码正在使用require来处理模块。我尝试排除 node_modules 文件夹,但未做任何更改。我认为,ES6模块使用编译模块作为依赖项放置到node_modules中,因为它不能被排除?有可能吗?

此外,我在理解笑话如何同时处理importrequire时遇到问题?如果首先编译ES6代码,则在该编译过程之后,每个模块将作为require处理。那是什么问题呢?

这是配置

jest.config.js

module.exports = {
  clearMocks: true,
  moduleNameMapper: {
    "^.+\\.(js|jsx)$": "babel-jest",
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/mocks/fileMock.js",
    "\\.(css|scss|sass|less)$":
      "<rootDir>/mocks/styleMock.js"
  },
  modulePathIgnorePatterns: [
    "node_modules/"
  ]
};

babel.config.js

/* eslint-disable */
module.exports = {
  presets: [
    "@babel/preset-react",
    [
      "@babel/preset-env",
      {
        targets: {
          browsers: ["ie >= 9", "safari >= 8"]
        }
      }
    ]
  ],
  plugins: [
    ["@babel/plugin-proposal-decorators", { legacy: true }],
    [
      "@babel/plugin-proposal-class-properties",
      { loose: true }
    ],
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-transform-object-assign",
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-transform-runtime"
  ],
  env:{
    test:{
      plugins: [
        ["@babel/plugin-proposal-decorators", { legacy: true }],
        [
          "@babel/plugin-proposal-class-properties",
          { loose: true }
        ],
        "@babel/plugin-proposal-object-rest-spread",
        "@babel/plugin-transform-object-assign",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-runtime"
      ]

    }
  }
};

0 个答案:

没有答案
相关问题