【问题标题】:Javascript: Unexpected token { - occurs when try to import custom class in typescript file into javascript fileJavascript: Unexpected token { - 尝试将 typescript 文件中的自定义类导入 javascript 文件时发生
【发布时间】:2019-11-14 23:55:44
【问题描述】:

我正在为 react-native 项目编写简单的 CLI 脚本。但我无法将类从打字稿导入到 javascript。它引发了以下错误。

从 './src/lib/modules/test-result' 导入 { TestResult };
SyntaxError: Unexpected token {...

package.json

...
"script": {
...
"formular:convert": "node convertor.js"
...
}
...

convertor.js

import {TestResult} from './src/lib/models/test-result';
...

test-result.ts

import uuid from 'uuid/v4';

import { Exception } from '../../errors';
import { OilTypes, RawMaterialTypes } from '../oils';

import { CalculatedResult } from './calculated-result';
import { DeviceSettings } from './device-settings';
import { DeviceStatus } from './device-status';
import { DisplayedResult } from './displayed-result';
import { Measurement } from './measurement';
import { PhoneInfo } from './phone-info';
import { PrimaryCompound } from './primary-compound';

export class TestResult {
    constructor(
        public id: string = uuid(),
        public createdAt: Date = new Date(),
        public updatedAt: Date = new Date(),
        public errors: Exception[] = [],
        public alias: string = '',
        public analyteTemp: number = 75,
        public flowerWeight: number = 0,
        public hidden: boolean = false,
        public note: string = '',
        public oilType: OilTypes = OilTypes.OliveOil,
        public primaryCompound: PrimaryCompound = PrimaryCompound.UNDEFINED,
        public units: string = '',
        public user: string = '',
        public air310Meas: Measurement = new Measurement(),
        public air280Meas: Measurement = new Measurement(),
        public analyte310Meas: Measurement = new Measurement(),
        public analyte280Meas: Measurement = new Measurement(),
        public calculated: CalculatedResult = new CalculatedResult(),
        public displayed: DisplayedResult = new DisplayedResult(),
        public status: DeviceStatus = new DeviceStatus(),
        public settings: DeviceSettings = new DeviceSettings(),
        public phoneInfo: PhoneInfo = new PhoneInfo(),
        public rawMaterialType: RawMaterialTypes = RawMaterialTypes.Isolate,
    ) {
    }
}

tsconfig.json

{
    "compilerOptions": {
        /* Basic Options */
        "target": "es5",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs",                  /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        // "lib": [],                             /* Specify library files to be included in the compilation. */
        "allowJs": true,                       /* Allow javascript files to be compiled. */
//        "checkJs": true,                       /* Report errors in .js files. */
        "jsx": "react",                 /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
                            /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        "removeComments": true,                /* Do not emit comments to output. */
        "noEmit": true,                        /* Do not emit outputs. */


        /* Strict Type-Checking Options */
        "strict": true,                        /* Enable all strict type-checking options. */

        /* Additional Checks */
        "noUnusedLocals": true,                /* Report errors on unused locals. */
        "noUnusedParameters": true,            /* Report errors on unused parameters. */
        "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

        /* Module Resolution Options */
        "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
        "types": [                             /* Type declaration files to be included in compilation. */
            "jest",
            "mocha",
            "detox"
        ],
        "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true,               /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

        /* Experimental Options */
        "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
        "skipLibCheck": true,                  /* Skip type checking of declaration files. Requires TypeScript version 2.0 or later. */
        "forceConsistentCasingInFileNames": true,/* Disallow inconsistently-cased references to the same file. */
        "resolveJsonModule": true              /* Include modules imported with '.json' extension. Requires TypeScript version 2.9 or later. */
    },
    "exclude": [
        "node_modules",
        "babel.config.js",
        "metro.config.js",
        "jest.config.js"
    ]
}

我努力寻找解决方案,并在这里和那里找到了一些答案,但所有这些都不起作用。

感谢您的帮助。

【问题讨论】:

  • 澄清一下,您是在尝试将 TypeScript 文件导入 JavaScript 文件吗?那是行不通的;你需要转换它们。 “转换器”应该做什么?
  • @Phix 你能告诉我如何转换它们吗?我是打字稿的新手。
  • 简答 - TypeScript 是 JS 的超集。我建议在网上做一些研究。

标签: javascript typescript react-native command-line-interface


【解决方案1】:

您正在运行 node convertor.js 并且 convertor.js 包含 import 语句:import {TestResult} from './src/lib/models/test-result'; 在您运行的节点版本中,这不是有效的语法,因此会出现错误。

修复

您需要使用 TypeScript (allowJs) 或 Babel 之类的东西来转译未转译的 .js 文件。

【讨论】:

  • 我在 tsconfig.json 文件中设置了 allowJs。 @basarat
  • @heltdev allowJs 告诉 TS 编译器允许 JavaScript 文件。更多here.
【解决方案2】:

我在尝试将 react-native-device-info 库与 react-native 0.59 一起使用时也遇到了这个问题。结果发现我的 package.json 中缺少 @babel/core 库。添加此模块后,错误消失了,我能够构建应用程序。

使用 npm 安装

npm i -s @babel/core

使用纱线安装

yarn add @babel/core

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2016-05-10
    • 2017-03-20
    • 1970-01-01
    • 2018-01-22
    • 2018-06-30
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多