我正在尝试将Typescript与Node和React一起使用。但是我正在努力设置Typescript编译器以使用正确类型的“模块约定”。我知道ES6模块可以正常工作,但Typescript总是生成一个非标准模块语法,由于某种原因,它只是不起作用。
如果我将此代码保存到.js
文件中,它可以正常工作:
import React, { Component } from 'react';
import './App.css';
let logo = require('./logo.svg');
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p>{logo}</p>
</div>
);
}
}
export default App;
但是,如果我将其保存到.tsx
文件,则会编译为:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
require("./App.css");
let logo = require('./logo.svg');
class App extends react_1.Component {
render() {
return (react_1.default.createElement("div", { className: "App" },
react_1.default.createElement("header", { className: "App-header" },
react_1.default.createElement("img", { src: logo, className: "App-logo", alt: "logo" }),
react_1.default.createElement("h1", { className: "App-title" }, "Welcome to React")),
react_1.default.createElement("p", { className: "App-intro" },
"To get started, edit ",
react_1.default.createElement("code", null, "src/App.js"),
" and save to reload."),
react_1.default.createElement("p", null, logo)));
}
}
exports.default = App;
导致节点错误react_1.default is undefined
。我尝试在Typescript编译器中添加esModuleInterop
标志,该标志添加了这个定义:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
}
并将require("react")
更改为__importDefault(require("react"))
。这解决了第一个问题,但react_1.Component
仍未定义。有没有办法将Typescript编译器设置为使用标准ES6模块?
答案 0 :(得分:2)
将此添加到tsconfig.json
:
"compilerOptions": {
"module": "es6"
}