Reactjs 如何为浏览器编译typescript
我有一个现有的项目,我想添加TypeScript和反应支持。由于该项目已经存在,我无法使用脚手架项目,并且在正确配置Reactjs 如何为浏览器编译typescript,reactjs,typescript,Reactjs,Typescript,我有一个现有的项目,我想添加TypeScript和反应支持。由于该项目已经存在,我无法使用脚手架项目,并且在正确配置tsconfig.json时遇到问题 根据我使用的设置,我一直有各种各样的问题,但通常我在/node\u modules/**和/node\u modules/@types/**中有不同代码的错误。我已经包括了我的tsconfig.json,以及关于每个设置修复了哪些错误的注释 如何在没有导入/模块问题的情况下编译TypeScript+React项目 当前相关tsconfig.js
tsconfig.json
时遇到问题
根据我使用的设置,我一直有各种各样的问题,但通常我在/node\u modules/**
和/node\u modules/@types/**
中有不同代码的错误。我已经包括了我的tsconfig.json
,以及关于每个设置修复了哪些错误的注释
如何在没有导入/模块问题的情况下编译TypeScript+React项目
当前相关tsconfig.json
settings
"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
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']
},
};
当前错误
ReferenceError:define未定义
(在浏览器中)如果您现在对单个文件感到满意,那么:
import
语句,以便TypeScript不会将其视为一个模块,只需参考React
和ReactDOM
全局变量,这些变量将在运行时由您在步骤1中添加的JavaScript文件定义。当代码不是模块时,@types/react
包将在编译时自动声明这些全局变量我最终使用
webpack
(带有ts加载程序
模块)而不是tsc
作为我的静态绑定器
我对我的打字脚本所做的唯一更改是将import React从“React”更改为import React代码>到导入*作为从“React”
进行的反应
tsconfig.json(缩写)
webpack.config.js
"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
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']
},
};
由于某些原因,我只能在浏览器中找到运行typescript编译器本身的搜索结果。该错误表示您试图加载AMD模块(“模块”:“AMD”
),而不使用与AMD兼容的模块加载程序。您可能不应该使用“模块”:“amd”
。在添加TypeScript之前,您使用了什么过程将JavaScript文件合并成一个文件?我可以尝试帮助您将TypeScript融入现有流程。之前我们没有进行任何传输。我认为单个文件是解决导入问题的最简单的解决方案,但我对任何解决方案都持开放态度。webpack.config.js