reactjs - 如何为浏览器编译 typescript

标签 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 (在浏览器中)

最佳答案

我最终使用了 webpack (使用 ts-loader 模块)而不是 tsc作为我的静态捆绑器。
我必须对我的 typescript 进行的唯一更改是更改 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.js
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']
    },
};

关于reactjs - 如何为浏览器编译 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52483853/

相关文章:

javascript - Reactjs - 函数在 map 函数内不起作用

javascript - 使用map方法返回一组新的数组

reactjs - 为什么关闭页面不会卸载组件

javascript - 如果您不想更改值,如何将默认值作为输入值传回?

Angular 2 : Find out if FormControl has required validator?

javascript - 使用 useEffect 钩子(Hook)获取后,ReactJS 上下文重新渲染

typescript :找不到名称要求

typescript - 如何在 TypeScript 的字符串文字中省略字符串

angular - 为什么我们在 angular2 中使用 moduleId :module. id

typescript - CallableContext 的导入是什么