我有一个想要添加 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/