Типизированный пакет в ASP. NET Core - PullRequest
0 голосов
/ 06 марта 2020

Я недавно обновил ASP. NET Core / React проект для использования TypeScript. Однако я заметил, что для того, чтобы компилировать TypeScript, мне нужно поместить импорт в начало файла. Когда упаковщик объединяет эти файлы, импорт не удаляется, и это приводит к ошибке import declarations may only appear at top level of a module. JSX, который выходит на другом конце, хорошо, кроме импорта. Есть ли способ заставить обработчик по умолчанию обрабатывать эти импорта?

bundleconfig. json

[
  {
    "outputFileName": "wwwroot/js/vehicles.jsx",
    "inputFiles": 
     [
       "built/Components/General/VehiclePanel.jsx",
       "built/Components/Vehicles/VehiclePage.jsx"
     ],
     "minify": 
     {
       "enabled": false,
       "renameLocals": false
     },
  },
  {
    "outputFileName": "wwwroot/js/editVehicle.jsx",
    "inputFiles": 
     [
       "built/Components/General/Job.jsx",
       "built/Components/General/History.jsx",
       "built/Components/General/EditVehiclePanel.jsx",
       "built/Components/Vehicles/EditVehiclePage.jsx"
     ],
     "minify": 
     {
       "enabled": false,
       "renameLocals": false
     },
  },
  {
    "outputFileName": "wwwroot/js/editService.jsx",
    "inputFiles": 
     [
       "built/Components/General/Job.jsx",
       "built/Components/General/History.jsx",
       "built/Components/General/ServicePanel.jsx",
       "built/Components/Services/ServicePage.jsx"
     ],
     "minify": 
     {
       "enabled": false,
       "renameLocals": false
     },
  },
]

Пример компонента с оператором импорта

// Name History.tsx
// Author: Redacted
// CreatedDate: 24/02/2020
// ModifiedDate: 29/02/2020
// Description: History panel
import { Component } from 'react';
import { IHistory } from "../../Interfaces/Interfaces";

interface HistoryProps {
    history: IHistory;
}

export class History extends Component<HistoryProps> {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <div className="box">
                    <div className="box-header with-border">
                        <h3 className="box-title">{this.props.history.title}</h3><div className="box-tools pull-right">{this.props.history.createdDateTime}</div>
                    </div>
                    <div className="box-body">
                        {this.props.history.description.split("\n").map(function (history, i) { return <p key={"h" + i}>{history}</p> })}
                    </div>
                </div>
            </div>
        );
    }

}

EDIT: я только что заметил, что скомпилированный компонент все еще имеет оператор export перед ним. Это заставляет меня думать, что это может иметь отношение к компиляции моего машинописного текста. Я добавил свой tsconfig. json на случай, если он уместен.

tsconfig. json

{
  "compileOnSave": true,
  "compilerOptions": {
    "outDir": "./built",
    "allowJs": true,
    "target": "es2015",
    "jsx": "preserve",
    "lib": [ "es2015", "es2016", "dom" ],
    "moduleResolution": "Node",
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "include": [
    "./Scripts/Components/**/*"
  ],
  "exclude": [
    "./Scripts/Interfaces/*"
  ]
}

2-е РЕДАКТИРОВАНИЕ: после добавления "module": "none" к compilerOptions в tsconfig. json операторы импорта и экспорта были удалены. К сожалению, это устранило эффект предыдущего изменения, которое я сделал. Я установил "moduleResolution": "Node" в compilerOptions, чтобы адрес был добавлен в начало всех файлов.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

1 Ответ

0 голосов
/ 06 марта 2020

Я решил проблему, когда это было добавлено в начало каждого файла.

Object.defineProperty(exports, "__esModule", { value: true });

Мне пришлось перенести экспорт в начало файла.

Я изменил его с это

import * as React from 'react';
import { IVehicle } from "../../Interfaces/Interfaces";

export class VehiclePanel extends React.Component<IVehicle> {

    constructor(props) {
        super(props);
    }

к этому

export = VehiclePanel;
import * as React from 'react';
import { IVehicle } from "../../Interfaces/Interfaces";

class VehiclePanel extends React.Component<IVehicle> {

    constructor(props) {
        super(props);
    }

...