Webpack Dev Server报错:Cannot GET /(TypeScript环境)求助
问题:TypeScript环境下Webpack Dev Server访问http://localhost:8080/出现Cannot GET /
在TypeScript环境运行Webpack Dev Server时,访问http://localhost:8080/ 出现错误:Cannot GET /。以下是相关配置文件及目录结构:
webpack.config.js
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: './src/index.ts', module: { rules: [ { test: /\.tsx$/, use: 'ts-loader', include: [path.resolve(__dirname, 'src')] }, ], }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, };
package.json
{ "name": "vault", "version": "1.0.0", "main": "index.js", "scripts": { "build": "webpack", "test": "echo \"Error: no test specified\" && exit 1", "serve": "webpack-dev-server" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "ts-loader": "^9.5.1", "typescript": "^5.6.2", "webpack": "^5.95.0", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.1.0" } }
tsconfig.json(注:当前配置为粘贴错误,实际内容与package.json重复,正确配置需修正)
{ "name": "vault", "version": "1.0.0", "main": "index.js", "scripts": { "build": "webpack", "test": "echo \"Error: no test specified\" && exit 1", "serve": "webpack-dev-server" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "ts-loader": "^9.5.1", "typescript": "^5.6.2", "webpack": "^5.95.0", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.1.0" } }
目录结构
根目录包含:
src文件夹(内有index.ts文件)webpack.config.jspackage.jsontsconfig.json
错误原因及修复方案
核心问题
- 无HTML入口文件:Webpack Dev Server需要HTML文件加载编译后的bundle.js,当前配置未生成或指定该文件,导致根路径无资源返回。
- Loader规则不匹配.ts文件:webpack.config.js中loader仅匹配
.tsx文件,入口.ts文件无法被编译。 - tsconfig.json配置错误:当前内容为package.json的复制粘贴错误,缺少TypeScript编译配置。
修复步骤
1. 安装HTML生成插件
执行命令安装html-webpack-plugin,用于自动生成HTML并注入bundle:
npm install --save-dev html-webpack-plugin
2. 修正webpack.config.js
更新配置,修复loader规则、添加插件与devServer配置:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.ts', module: { rules: [ { test: /\.tsx?$/, // 匹配.ts和.tsx文件 use: 'ts-loader', include: [path.resolve(__dirname, 'src')], exclude: /node_modules/ }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], // 配置模块解析扩展名 }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), clean: true // 构建时清空dist目录 }, plugins: [ new HtmlWebpackPlugin({ title: 'TypeScript Webpack Demo', // 自动生成HTML的标题 // 若需要自定义模板,可添加template: './public/index.html'并创建对应文件 }) ], devServer: { port: 8080, open: true // 启动后自动打开浏览器 }, mode: 'development' // 指定开发模式 };
3. 修正tsconfig.json
替换为标准TypeScript编译配置:
{ "compilerOptions": { "target": "ES5", "module": "ESNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"], "exclude": ["node_modules"] }
4. 重启Dev Server
执行命令:
npm run serve
此时访问http://localhost:8080/ 即可正常加载页面,Webpack会自动将编译后的bundle.js注入到生成的HTML中。
内容的提问来源于stack exchange,提问作者Boris Georgiev
相关产品推荐
相关产品推荐

