我试图调试VSCode中的一些Typescript代码,但是每次尝试调试时,我的index.tsx(这是我的React App的入口)都会得到“未定义文档”的信息。我正在使用webpack将Typescript编译为javascript。
packages.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/jest": "23.3.13",
"@types/node": "10.12.19",
"@types/react": "16.7.22",
"@types/react-dom": "16.0.11",
"axios": "^0.18.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-scripts": "2.1.3",
"ts-loader": "^5.3.3",
"typescript": "3.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"jsx": "react",
"module": "commonjs",
"types": ["node"],
"sourceMap": true
},
"exclude": [
"node_modules"
]
}
webpack.config.js
module.exports = {
mode: "development",
devtool: "inline-source-map",
entry: "./src/index.tsx",
devtool: "cheap-source-map",
output: {
filename: "bundle.js",
publicPath: "./dist",
devtoolModuleFilenameTemplate: '[absolute-resource-path]'
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{ test: /\.tsx?$/, loader: "ts-loader" }
]
}
};
launch.json
"version": "0.2.0",
"configurations": [
{
"name": "Launch Program",
"type": "node",
"request": "launch",
"cwd": "${workspaceRoot}",
"program": "${workspaceRoot}/src/index.tsx",
"outFiles": [
"${workspaceRoot}/dist/bundle.js"
],
"sourceMaps": true
}
]
}
调试时,可以进入index.tsx文件的第一部分:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App'
ReactDOM.render(<App />, document.getElementById("root"));
但是在document.getElementById(“ root”))处失败;并说“文档”未定义
ReferenceError: document is not defined
at Object../src/index.tsx