Babel使用Webpack进行编译,但不使用Jest进行编译

时间:2018-05-04 11:44:21

标签: node.js webpack babeljs jestjs es6-class

我正在尝试使用带有env预设的Babel来设置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: Class constructor EventPubSub cannot be invoked without 'new'

   99 |   midi
  100 | 
> 101 |   constructor() {
  102 |     super()
  103 | 
  104 |     // request MIDI access

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

1 个答案:

答案 0 :(得分:0)

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

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

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