简体   繁体   English

使用Webpack / Babel运行业力时出现``意外字符串''

[英]'Unexpected string' when running karma with webpack/babel

I'm trying to run karma using webpack to preprocess code with babel that can then be tested with mocha. 我正在尝试使用webpack运行业力以使用babel预处理代码,然后可以使用mocha对其进行测试。 However whenever I run it I get errors. 但是,每当我运行它时,我都会出错。

spec/tests.spec.js: 投机/ tests.spec.js:

import 'chai/register-expect';

karma.conf.js: karma.conf.js:

const webpackConfig = require('./webpack.config.js');

const tests = './spec/**/*.spec.js'

module.exports = function(config) {
  config.set({
    singleRun: true,
    browsers: ['Chrome'],
    frameworks: ['mocha'],
    files: [
      tests
    ],
    preprocessors: {
      tests: ['webpack'],
    },
    webpack: webpackConfig,
  })
}

webpack.config.js: webpack.config.js:

module.exports = {
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', {
            'modules': false
          }]
        }
      }
    ]
  }
}

When I run karma I get the following output: 运行业力时,得到以下输出:

'Uncaught SyntaxError: Unexpected string\\nat http://localhost:9876/base/spec/tests.spec.js?af68737606dd067ef21aa6efadfc004fb1d05454:1:8 \\n '未捕获的SyntaxError:意外的字符串\\ nat http:// localhost:9876 / base / spec / tests.spec.js?af68737606dd067ef21aa6efadfc004fb1d05454:1:8 \\ n

Which corresponds to the import line. 对应于import行。

If I remove all es6 code from the test, then it runs successfully, implying that webpack/babel isn't being invoked properly. 如果我从测试中删除了所有es6代码,则它将成功运行,这表明未正确调用webpack / babel。

Any ideas why this isn't working? 任何想法为什么这不起作用?

So it was nothing to do with any of the tools, and turned out to be a JS gotcha. 因此,它与任何工具都没有关系,结果证明是JS陷阱。

In karma.conf.js I was doing: 在karma.conf.js中,我正在执行以下操作:

const tests = './spec/**/*.spec.js'
...
    preprocessors: {
      tests: ['webpack'],
    }

The problem here is that tests as an object key translates to the string "tests" . 这里的问题是将tests作为对象键转换为字符串"tests"

The solution was to use: 解决方案是使用:

preprocessors: {
  [tests]: ['webpack'],
}

So that tests gets expanded properly to the variable value. 这样tests就可以正确地扩展到变量值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM