【问题标题】:Unexpected reserved word error while testing using wallaby使用小袋鼠测试时出现意外的保留字错误
【发布时间】:2016-05-05 21:50:19
【问题描述】:

在我编写测试用例的测试文件中,我导入了如下的打字稿文件:

import {rootReducer} from "../src/reducers/rootReducer";

在 rootReducer.ts 中,我导入了另一个 typescript 文件,如下所示:

import taskReducer from "./taskReducer.ts";

然后显示错误:

SyntaxError: Unexpected reserved word
at src/reducers/rootReducer.ts:7

rootReducer.ts 和 taskReducer.ts 都在文件夹 /src/reducers 下

如果您从导入语句中删除“.ts”,则不会失败测试,​​但会在浏览器中引发错误。该应用程序将无法运行

小袋鼠配置如下:

module.exports = function (wallaby) {

    return {
        files: [
            'src/*.ts',
            'src/**/*.ts'
        ],

        tests: [
            'test/*Test.ts'
        ],

        testFramework: "mocha",

        env: {
            type: 'node'
        },

        compilers: {
            '**/*.ts': wallaby.compilers.typeScript({
                /* 1 for CommonJs*/
                module: 1
            })
        }
    }
};

【问题讨论】:

  • 您确定这不是因为您在第二次导入中缺少 { } 吗?看起来像是语法错误。
  • 我曾尝试在第二次导入中添加 {}。仍然显示相同的错误。我猜这是我在小袋鼠配置中错过的东西,因为当我删除扩展名“.ts”时,就没有小袋鼠错误
  • 您需要从导入中删除 .ts,否则您只是将 TypeScript 文件加载为 JavaScript,因此会出现错误。
  • 如果我从导入中删除 .ts,浏览器将读取其 js 文件而不是 ts,这会导致一些问题,并且应用程序将无法在浏览器中运行。有什么方法可以让它同时在小袋鼠和浏览器中工作?
  • 我不知道你为什么需要在浏览器中加载 ts 而不是 js,你的构建过程/模块捆绑器应该为你的浏览器正确编译东西。无论如何,请创建一个示例存储库来展示您的问题,乐于研究它并提供帮助。

标签: typescript wallaby.js


【解决方案1】:

您的陈述:

import taskReducer from "./taskReducer.ts";

应该是:

// Import just taskReducer from this module
import {taskReducer} from "./taskReducer";

或者:

// Import the whole module and call it taskReducer
import * as taskReducer from "./taskReducer";

【讨论】:

  • 这两个都试过了。仍然显示相同的错误。如果我删除扩展名“.ts”,小袋鼠不会显示任何错误。但是浏览器抛出错误,应用程序无法运行
  • @DixyXavier 你不应该需要 .ts 文件。模块加载器应该在符文时加载 .js 文件。 :-/
  • 如果我从导入中删除 .ts,浏览器将读取其 js 文件而不是 ts,这会导致一些问题,并且应用程序将无法在浏览器中运行。有什么方法可以让它在小袋鼠和浏览器中都可以工作?
【解决方案2】:

问题不在于 wallaby.js,而在于您的 webpack 配置。要在不指定扩展名的情况下启用需要文件,您必须添加一个 resolve.extensions 参数,指定 webpack 搜索哪些文件:

// webpack.config.js
module.exports = {
  ...
  resolve: {
    // you can now require('file') instead of require('file.ts')
    extensions: ['', '.js', '.ts', '.tsx'] 
  }
};

【讨论】:

  • 谢谢阿特姆。你永远是我的救星:)
猜你喜欢
  • 2022-10-24
  • 2020-04-28
  • 2016-06-27
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 2021-02-06
  • 2018-01-04
相关资源
最近更新 更多