如何为浏览器编译打字稿

时间:2018-09-24 16:41:28

标签: reactjs typescript

我有一个现有项目,我想向其中添加TypeScript和React支持。因为该项目已经存在,所以我不能使用脚手架项目,并且无法正确配置tsconfig.json

根据使用的设置,我一直遇到各种问题,但是通常我在/node_modules/**中经常遇到不同的错误,而在/node_modules/@types/**中经常有错误。我已在tsconfig.json的注释中列出了每个设置可解决的错误。

如何在没有导入/模块问题的情况下编译我的TypeScript + React项目?

当前相关的tsconfig.json设置

"module": "amd", // must be 'amd' or 'system' to use 'outFile'
"lib": ["es2015", "dom", "es5", "es6"], // must include some of these to suppress certain errors; adds the 'Set' type
"jsx": "react", // compile jsx to js
"sourceMap": true, // ensure debuggable
"outFile": "./static/js/app.js", // must be under /static/ to be served
"rootDir": "./static/ts",
"moduleResolution": "node", // suppresses issue with `default` or `export`
"esModuleInterop": true

当前错误

ReferenceError: define is not defined(在浏览器中)

2 个答案:

答案 0 :(得分:1)

我最终使用webpack(带有ts-loader模块)而不是tsc作为我的静态捆绑器。

我对打字稿所做的唯一更改是将import React from "react";更改为import * as React from "react"

tsconfig.json (摘要)

"target": "es5",
"module": "commonjs",
"lib": ["es5", "es6", "dom"],
"allowJs": true,
"jsx": "react",
"sourceMap": true,
"rootDir": "./client",
"downlevelIteration": true,

webpack.config.json

const path = require('path');

module.exports = {
    context: path.resolve(__dirname, 'client'),
    devtool: 'inline-source-map',
    entry: './main.tsx',
    mode: 'development',
    module: {
        rules: [{
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        }]
    },
    output: {
        filename: 'client.js',
        path: path.resolve(__dirname, 'static/js')
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.jsx', '.js']
    },
};

答案 1 :(得分:0)

如果您现在对单个文件感到满意,那么:

  1. 如果还没有这样做,请遵循these instructions将React库添加到您的页面。 (您可以根据需要下载JavaScript文件并将其托管在服务器上)
  2. 从文件中删除import语句,以使TypeScript不会将其视为模块,而只是引用将在运行时定义的ReactReactDOM全局变量由您在步骤1中添加的JavaScript文件决定。@types/react包将在代码不是模块时的编译时自动声明这些"UMD"全局变量。