首页 文章

Babel用Webpack编译但不用Jest编译

提问于
浏览
0

我正在尝试使用Babel和 env 预设来设置Jest以使用我的ES6项目 . 代码编译和使用Webpack但不与Jest一起使用 . 问题似乎是来自 node_modules 内部的转换代码 .

package.json(yarn):

{
  "name": "generative-toolbox",
  "version": "0.0.1",
  "main": "toolbox.js",
  "repository": "git@bitbucket.org:yojeek/generative-toolbox.git",
  "author": "msamoylov <antiplaka@gmail.com>",
  "license": "MIT",
  "private": true,
  "scripts": {
    "build": "yarn webpack --config webpack.config.js",
    "test": "jest --debug"
  },
  "devDependencies": {
    "babel-jest": "^22.4.3",
    "jest": "^22.4.3",
    "regenerator-runtime": "^0.11.1",
    "webpack-cli": "^2.1.2"
  },
  "dependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.6.1",
    "babel-register": "^6.26.0",
    "dat.gui": "^0.7.1",
    "enumify": "^1.0.4",
    "event-pubsub": "^4.3.0",
    "webpack": "^4.6.0"
  },
  "babel": {
    "presets": [
      ["env"],
      "stage-2"
    ],
    "env": {
      "test": {
        "presets": [
          ["env", {
            "targets": {
              "node": "9.4.0"
            },
            "debug": true
          }],
          "stage-2"
        ]
      }
    }
  }
}

webpack.config.js:

var path = require("path");

module.exports = {
  entry: "./toolbox.js",
  mode: 'development',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "generative.toolbox.js",
    publicPath: '/dist/',
    library : "GenT"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
}

toolbox.js中的定义:

import EventPubSub from 'event-pubsub'

class GUI {
  gui
  config
  values

  constructor() {
    // some valid code
  }
}


class MIDI extends EventPubSub {
  midi

  constructor() {
    super()

    // some valid code down there
  }
}

test.js:

import {GUI, MIDI} from './toolbox.js'

test('gui sanity', () => { // <--- pass
  let gui = new GUI()
  expect(gui).toBeTruthy()
});

test('midi sanity', () => { // <--- fail
  let midi = new MIDI()
  expect(midi).toBeTruthy()
});

测试失败,结果如下:

TypeError:没有'new',不能调用类构造函数EventPubSub

99 | MIDI
100 |

101 | constructor(){
102 |超()
103 |
104 | //请求MIDI访问

在新的MIDI(toolbox.js:101:17)
at Object . <anonymous>(test.js:15:14)

1 回答

  • 0

    所以,因为我想在 node_modules 内扩展ES6类,我必须在jest配置中明确地排除它:

    "jest": {
        "transformIgnorePatterns": [
          "/node_modules/(?!event-pubsub).+\\.js$"
        ]
      }
    

    这样,模块将被导入到我的测试中(不会被转换) .

相关问题