Ошибка сборки модуля: SyntaxError: «импорт» и «экспорт» могут отображаться только с «sourceType: модуль»

При запуске тестов с покрытием кода через angular-cli (ng test -cc) карма выдает ошибку ниже. Виновником, по-видимому, является модуль покрытия кода istanbul, поскольку выполнение тестов без -cc не приводит к каким-либо ошибкам.

Ошибка (я заменил локальные пути на ***):

at Object.exports.default (***\node_modules\istanbul-instrumenter-loader\dist\index.js:25:16),Module build failed: SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"' (1:0)
    at Parser.pp$5.raise (***\node_modules\babylon\lib\index.js:4454:13)
    at Parser.pp$1.parseStatement (***\node_modules\babylon\lib\index.js:1881:16)
    at Parser.parseStatement (***\node_modules\babylon\lib\index.js:5910:22)
    at Parser.pp$1.parseBlockBody (***\node_modules\babylon\lib\index.js:2268:21)
    at Parser.pp$1.parseTopLevel (***\node_modules\babylon\lib\index.js:1778:8)
    at Parser.parse (***\node_modules\babylon\lib\index.js:1673:17)
    at Object.parse (***\node_modules\babylon\lib\index.js:7305:37)
    at Instrumenter.instrumentSync (***\node_modules\istanbul-lib-instrument\dist\instrumenter.js:121:31)
    at Instrumenter.instrument (***\node_modules\istanbul-lib-instrument\dist\instrumenter.js:176:32)
    at Object.exports.default (***\node_modules\istanbul-instrumenter-loader\dist\index.js:25:16)
    at Compiler.compiler.plugin (***\node_modules\@angular\cli\plugins\karma-webpack-throw-error.js:10:23)
    at Compiler.applyPlugins (***\node_modules\tapable\lib\Tapable.js:61:14)
    at Watching._done (***\node_modules\webpack\lib\Compiler.js:92:17)
    at onCompiled (***\node_modules\webpack\lib\Compiler.js:51:17)
    at ***\node_modules\webpack\lib\Compiler.js:494:13
    at next (***\node_modules\tapable\lib\Tapable.js:202:11)
    at Compiler.<anonymous> (***\node_modules\webpack\lib\CachePlugin.js:62:5)
    at Compiler.applyPluginsAsyncSeries (***\node_modules\tapable\lib\Tapable.js:206:13)
    at ***\node_modules\webpack\lib\Compiler.js:491:10
    at Compilation.applyPluginsAsyncSeries (***\node_modules\tapable\lib\Tapable.js:195:46)
    at self.applyPluginsAsync.err (***\node_modules\webpack\lib\Compilation.js:645:19)
    at next (***\node_modules\tapable\lib\Tapable.js:202:11)
    at Compilation.compilation.plugin (***\node_modules\webpack\lib\ProgressPlugin.js:121:6)
    at Compilation.applyPluginsAsyncSeries (***\node_modules\tapable\lib\Tapable.js:206:13)
    at self.applyPluginsAsync.err (***\node_modules\webpack\lib\Compilation.js:636:11)
    at next (***\node_modules\tapable\lib\Tapable.js:202:11)

пакет.json:

{
  "name": "texteditorapplication",
  "version": "1.1.0",
  "license": "MIT",
  "scripts": {
    ***
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "4.2.3",
    "@angular/common": "4.2.3",
    "@angular/compiler": "4.2.3",
    "@angular/core": "4.2.3",
    "@angular/forms": "4.2.3",
    "@angular/http": "4.2.3",
    "@angular/platform-browser": "4.2.3",
    "@angular/platform-browser-dynamic": "4.2.3",
    "@angular/router": "4.2.3",
    "@ngrx/core": "1.2.0",
    "@ngrx/db": "2.0.2",
    "@ngrx/effects": "2.0.3",
    "@ngrx/router-store": "1.2.6",
    "@ngrx/store": "2.2.2",
    "@ngrx/store-devtools": "3.1.0",
    "@ngrx/store-log-monitor": "3.0.2",
    "bootstrap": "3.3.7",
    "core-js": "2.4.1",
    "linqts": "1.8.2",
    "loader-utils": "^1.1.0",
    "ngrx-store-freeze": "0.1.0",
    "ngx-bootstrap": "2.0.0-beta.2",
    "rxjs": "5.4.1",
    "web-animations-js": "2.2.2",
    "typescript": "2.3.4",
    "zone.js": "0.8.6"
  },
  "devDependencies": {
    "@angular/cli": "1.2.7",
    "@angular/compiler-cli": "4.2.3",
    "@ngrx/store": "^2.2.1",
    "@types/jasmine": "2.5.38",
    "@types/node": "6.0.64",
    "@types/reflect-metadata": "0.0.5",
    "codelyzer": "2.0.1",
    "copyfiles": "1.2.0",
    "enhanced-resolve": "3.3.0",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "1.7.1",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "0.2.2",
    "karma-phantomjs2-launcher": "v0.5.0",
    "karma-coverage-istanbul-reporter": "1.3.0",
    "istanbul-instrumenter-loader": "3.0.0",
    "less-cli": "1.0.0",
    "phantomjs-prebuilt": "v2.1.16",
    "protractor": "5.1.0",
    "rimraf": "2.6.1",
    "ts-node": "2.0.0",
    "tslint": "4.5.0",
    "typescript": "2.3.4"
  }
}

карма.conf.json

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('@angular/cli/plugins/karma'),
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts', 'tsx']
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    customLaunchers: {
      "ChromeHeadless": {
        base: 'Chrome',
        flags: ['--headless', '--remote-debugging-port=9222', '--no-sandbox']
      }
    },
    singleRun: false
  });
};

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "es6",
    "typeRoots": [
      "node_modules/@types"
    ],
    "paths": {
      "@angular/*": [
        "../node_modules/@angular/*"
      ],
      "@ngrx/*": [
        "../node_modules/@ngrx/*"
      ],
      "ngx-bootstrap/*": [
        "../node_modules/ngx-bootstrap/*"
      ],
      "rxjs/*": [
        "../node_modules/rxjs/*"
      ],
      "afw/*": [
        "../node_modules/afw/*"
      ]
    },
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

tsconfig.spec.json

{
  "extends": "../tsconfig.json",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module"
  },
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "module": "commonjs",
    "target": "es5",
    "outDir": "../out-tsc/spec",
    "baseUrl": "",
    "types": [
      "jasmine",
      "node"
    ],
    "traceResolution": true
  },
  "files": [
    "test.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

Пожалуйста, помогите, так как я не могу найти решение, и теперь я также потерял возможность не переворачивать таблицу, когда сталкиваюсь с этой ошибкой. У меня заканчиваются столы.


person shmow    schedule 14.12.2017    source источник
comment
Вы когда-нибудь исправляли это?   -  person whizzzkid    schedule 27.06.2019


Ответы (1)


karma.conf.js

config.set({
  ...
  files: [
    'test/index.js'
  ],
  preprocessors: {
    'test/index.js': 'webpack'
  },
  webpack: {
    ...
    module: {
      rules: [
        // instrument only testing sources with Istanbul 
        {
          test: /\.js$/,
          use: { loader: 'istanbul-instrumenter-loader' },
          include: path.resolve('src/components/')
        }
      ]
    }
    ...
  },
  reporters: [ 'progress', 'coverage-istanbul' ],
  coverageIstanbulReporter: {
    reports: [ 'text-summary' ],
    fixWebpackSourcePaths: true
  }
  ...
});

Как написано в https://www.npmjs.com/package/istanbul-instrumenter-loader вы должны включить свой пакет в karma.conf.js;

У вас есть только instanbul-reporter, а не instrumenter-loader в вашей конфигурации. Попробуйте добавить его.

Надеюсь, это помогло

person Luca Taccagni    schedule 25.01.2018
comment
Мы используем реализацию Angular CLI, которая работает немного иначе, чем базовый пакет istanbul-reporter. - person shmow; 05.02.2018