Karma问题Javascript import SyntaxError

时间:2016-04-28 19:12:18

标签: javascript angularjs karma-jasmine gulp-karma

我正在尝试运行此规范,我收到此错误: SyntaxError:import声明只能出现在模块的顶层

但是如你所见,我有最重要的导入,那么可能还有其他原因吗?

纳克外形builder.spec.js

import angular from "angular";
import mocks from "angular-mocks";
import "src/ng-form-builder.js";

var inject = mocks.inject;
var module = mocks.module;

describe('ng-form-builder', function () {
  var scope, $compile, $rootScope, element;

  function createDirective(template) {
    var elm;

    elm = angular.element(template);
    angular.element(document.body).prepend(elm);
    $compile(elm)(scope);
    scope.$digest();

    return elm;
  }

  beforeEach(module('ngSanitize', 'peoplewareDo.ng-form-builder'));
  beforeEach(inject(function(_$rootScope_, _$compile_) {
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    $compile = _$compile_;
  }));

纳克外形builder.js

(function () {

'use strict';

angular.module('peoplewareDo.ng-form-builder', []).directive('ngFormBuilder', function () {
   ....
});

// coffeescript's for in loop
var __indexOf = [].indexOf || function(item) {
        for (var i = 0, l = this.length; i < l; i++) {
            if (i in this && this[i] === item) return i;
        }
        return -1;
    };

angular.module('peoplewareDo.ng-form-builder', []).directive('ngFormField', function($http, $compile) {
...

});

}());

控制台日志

[vns@localhost ng-form-builder]$ gulp test
[15:01:07] Using gulpfile ~/workspace/ng-form-builder/gulpfile.js
[15:01:07] Starting 'clean'...
[15:01:07] Starting 'scripts'...
[15:01:07] Finished 'scripts' after 65 ms
[15:01:07] Starting 'styles'...
[15:01:07] Starting 'jshint-test'...
[15:01:07] Starting 'karma'...
[15:01:07] Finished 'clean' after 205 ms
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser Firefox
[15:01:08] Finished 'jshint-test' after 346 ms
[15:01:08] Finished 'styles' after 500 ms
[15:01:08] Starting 'build'...
[15:01:08] Finished 'build' after 6.5 μs
INFO [Firefox 45.0.0 (Fedora 0.0.0)]: Connected on socket saObD8MsBt0Hw9swPwC5 with id 21261564
Firefox 45.0.0 (Fedora 0.0.0) ERROR
  SyntaxError: import declarations may only appear at top level of a module
  at /home/vns/workspace/ng-form-builder/test/ng-form-builder.spec.js:1
[15:01:11] 'karma' errored after 4.06 s
[15:01:11] Error: 1
    at formatError (/usr/lib/node-v5.7.0-linux-x64/lib/node_modules/gulp/bin/gulp.js:169:10)
    at Gulp.<anonymous> (/usr/lib/node-v5.7.0-linux-x64/lib/node_modules/gulp/bin/gulp.js:195:15)
    at emitOne (events.js:90:13)
    at Gulp.emit (events.js:182:7)

2 个答案:

答案 0 :(得分:1)

问题是Firefox,这个代码执行的浏览器可以在这里看到:

INFO [Firefox 45.0.0 (Fedora 0.0.0)]: Connected on socket saObD8MsBt0Hw9swPwC5 with id 21261564
Firefox 45.0.0 (Fedora 0.0.0) ERROR

完全不支持ES6。为了运行此代码,需要从ES6到ES5的透明化。

答案 1 :(得分:0)

import是ES2015的功能,目前许多浏览器都不支持此功能。使用Babel - 一个从EC2015到ES5编译的javascript编译器。