“ SyntaxError:意外令牌{”:tsconfig无法将node_modules中的文件识别为有效的打字稿

时间:2019-07-17 23:43:55

标签: angular typescript protractor tsconfig

我正在从我的node_modules文件夹中的自定义包中引用一个简单的函数,并意识到它正在尝试以javascript而不是打字稿的形式读取文件。我需要在tsconfig.json中修改哪些设置才能使其正常工作?

我尝试将accessibilityCheck函数包装在一个类中,并使其成为模块的一部分,并从自定义包中导出该模块以用于测试。还尝试将import语句替换为require语句。

tsconfig.json

const { ApolloServer } = require('apollo-server-express');
const express = require('express');

const PORT = 4000;
const app = express();
const server = new ApolloServer({ typeDefs, resolvers });

server.applyMiddleware({app, path: custom_endpoint})

const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

// ⚠️ Pay attention to the fact that we are calling `listen` on the http server variable, and not on `app`.
httpServer.listen(PORT, () => {
  console.log(`? Server ready at http://localhost:${PORT}${server.graphqlPath}`) //this changes to my custom_endpoint
  console.log(`? Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`) // this does not chnage to my custome_endpoint.```

e2e-utilities是一个自定义程序包,我们将其导入到当前项目中

node_modules / e2e-utilties / accessibility-check.ts

{
  "compileOnSave": false,
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2016"
    ],
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc-e2e",
    "sourceMap": true,
    "target": "es6",
    "typeRoots": [
      "../node_modules/@types"
    ]
  },
  "include": ["../node_modules/e2e-utilities/*.ts"]
}

测试文件

import { browser } from 'protractor';
import { AxeResults } from 'axe-core';
import { SarifLog, convertAxeToSarif } from 'axe-sarif-converter';
const util = require('util');
const fs = require('fs');
const path = require('path');
const axeBuilder = require('axe-webdriverjs');

export async function accessibilityCheck(
    fileName: string,
    selectorsToExclude?: string[],
    selectorsToInclude?: string[]): Promise<AxeResults> {
    const builder = axeBuilder(browser.driver);
    if (selectorsToInclude) {
        selectorsToInclude.forEach(selector => builder.include(selector));
    }
    if (selectorsToExclude) {
        selectorsToExclude.forEach(selector => builder.exclude(selector));
    }
    const axeResults: AxeResults = await builder.analyze();

    const sarifResults: SarifLog = convertAxeToSarif(axeResults);
    const a11yResultsFilepath = path.join(__dirname, '../..', 'accessibilityresults');
    if (!fs.existsSync(a11yResultsFilepath)) {
        await util.promisify(fs.mkdir)(a11yResultsFilepath);
    }
    const filepath = path.join(a11yResultsFilepath, fileName);
    await util.promisify(fs.writeFile)(filepath, JSON.stringify(sarifResults));
    return axeResults;
}

protractor.conf.js

describe('Accessibility demo', () => {
    it('Running accessibility check on dashboard', async () => {
        const results = await accessibilityCheck('attract-dashboard.sarif', ['#talent-header'], []);
    });
});
const { SpecReporter } = require('jasmine-spec-reporter');
const VideoReporter = require('protractor-video-reporter');
const Path = require('path');

exports.config = {
    allScriptsTimeout: 11000,
    useAllAngular2AppRoots: true,
    specs: [
        Path.join('../../../../../', '/e2e/accessibility/**/*.a11y-spec.ts')
    ],
    capabilities: {
        'browserName': 'chrome',
        chromeOptions: {
            args: [
                '--start-maximized'
            ]
        }
    },
    chromeOnly: true,
    directConnect: true,
    baseUrl: 'https://localhost:443/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 110000,
        print: function () { }
    },
    beforeLaunch: function () {
        require('ts-node').register({
            project: 'e2e/tsconfig.json'
        });
    },
    onPrepare: function () {

        // Overrides default format of .mov to .avi to work in windows
        VideoReporter.prototype.jasmineStarted = function() {
            var self = this;
            if (self.options.singleVideo) {
                var videoPath = Path.join(self.options.baseDirectory, 'protractor-accessibility-specs.avi');
                self._startScreencast(videoPath);

                if (self.options.createSubtitles) {
                    self._subtitles = [];
                    self._jasmineStartTime = new Date();
                }
            }
        };

        console.log(process.env.DISPLAY)

        jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
        var failFast = require('jasmine-fail-fast');
        jasmine.getEnv().addReporter(failFast.init());
        jasmine.getEnv().addReporter(new VideoReporter({
            baseDirectory: Path.join(__dirname, 'a11y_report', Date.now().toString()),
            createSubtitles: true,
            singleVideo: true,
            ffmpegCmd: Path.normalize('C:/ffmpeg/bin/ffmpeg.exe'),
            ffmpegArgs: [
                '-f', 'gdigrab',
                '-framerate', '30',
                '-i', 'desktop',
                '-q:v','5'
            ]
          }));
    }
};

我反而希望此文件像普通的打字稿文件一样被解析,而不是像javascript文件那样解析并失败。

1 个答案:

答案 0 :(得分:1)

节点模块通常应该预先捆绑在一起。当您遇到这种类型的错误时,请库开发人员提前进行翻译,并包括声明以保持类型安全。