ts-loader无法识别TypeScript语法,编译时报缺少分号错误
ts-loader无法识别TypeScript语法问题排查
问题概述
使用ts-loader编译TypeScript文件时,出现语法错误:SyntaxError: Missing semicolon. (1:5),测试文件仅包含基础的TypeScript类型注解代码。
现有配置
webpack.config.js(项目根目录)
//@ts-check const path = require('path'); const webpack = require('webpack'); /** * @type {import('webpack').Configuration} */ const config = { entry: './source/test.index.ts', mode: 'production', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.module.css$/, use: [ { loader: "css-loader", options: { esModule: true, modules: true, }, }, ], }, { test: /\.(tsx|jsx|ts|js)?$/, use: "babel-loader", exclude: /node_modules/, } ], }, resolve: { extensions: ['.tsx', '.ts', '.js', '.jsx', '', '.*'], alias: { 'react/hooks': 'preact/hooks', 'react': 'preact/compat', 'react-dom': 'preact/compat', }, }, output: { path: path.resolve(__dirname, 'dist\\webpack'), filename: 'webpack.bundle.js', }, }; module.exports = config;
tsconfig.json(项目根目录)
{ "compilerOptions": { "target": "ES5", "outDir": "./release/built", "jsx": "react-jsx", "rootDir": "./", "jsxImportSource": "preact", "allowJs": true, "strict": false, "esModuleInterop": true, "moduleResolution": "Node", "module": "ES2020", "plugins": [ { "name": "typescript-plugin-css-modules", "options": { "classnameTransform": "dashes", "customMatcher": "\\.module\\.css$", "dotenvOptions": {}, "postcssOptions": {}, "rendererOptions": {} } } ], "skipLibCheck": true, "baseUrl": "./", "paths": { "react": [ "./node_modules/preact/compat/" ], "react/jsx-runtime": [ "./node_modules/preact/jsx-runtime" ], "react-dom": [ "./node_modules/preact/compat/" ], "react-dom/*": [ "./node_modules/preact/compat/*" ] } }, "include": [ "./source/test.index.ts" ] }
测试文件
source/test.index.ts内容:
let r: string = '44' console.log(r)
错误信息
SyntaxError: Missing semicolon. (1:5)
原因分析
webpack的module.rules中,babel-loader的规则匹配了.ts/.tsx文件,而babel默认不支持TypeScript的类型注解语法。当babel-loader处理TS文件时,会将let r: string中的类型注解视为非法JS语法,从而抛出误判的分号缺失错误。
解决方案
方案一:限制babel-loader仅处理JS/JSX文件
修改webpack.config.js中babel-loader的规则,缩小匹配范围,避免处理TS文件:
{ // 仅匹配.js和.jsx文件 test: /\.(jsx|js)$/, use: "babel-loader", exclude: /node_modules/, }
方案二:配置babel支持TypeScript(如需用babel处理TS)
如果需要保留babel-loader对TS文件的处理(比如结合babel生态插件),需安装并配置@babel/preset-typescript:
- 安装依赖:
npm install @babel/preset-typescript --save-dev
- 在项目根目录创建/修改
.babelrc或babel.config.json:
{ "presets": ["@babel/preset-typescript"] }
- 可选:调整ts-loader配置,让ts仅做类型检查,转译交给babel:
{ test: /\.tsx?$/, use: { loader: 'ts-loader', options: { configFile: './tsconfig.json', // 仅做类型检查,转译由babel完成 transpileOnly: true } }, exclude: /node_modules/, }
额外检查
确保ts-loader正确读取tsconfig.json,可在ts-loader的options中显式指定配置文件路径(如上述方案二中的配置),避免因路径问题导致配置不生效。
内容的提问来源于stack exchange,提问作者Александр
相关产品推荐
相关产品推荐

