如何在Webpack+TypeScript项目中正确显示变音符号
Webpack + TypeScript 变音符号乱码问题
问题现象
- Webpack搭配TypeScript构建后,德语、波兰语等含变音符号的字符(如ü、ö、ą、ś)在控制台和页面显示乱码
- 直接使用JS文件时无此问题,页面已设置
<meta charset="UTF-8">标签 - 具体表现:
- TypeScript源码:
console.log('ü, ö, ä ą, ś, ć, ł') - Webpack编译后的bundle.js:
console.log('�, �, � �, �, �, �'); - 页面及控制台输出对应乱码字符
- TypeScript源码:
相关配置文件
webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const path = require('path'); // 补充缺失的path模块引入 module.exports = { mode: 'development', entry: './ts/index.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, resolve: { extensions: ['.ts', '.js', '.scss'], }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { encoding: 'utf-8', presets: ['@babel/preset-env'], plugins: [ ['@babel/plugin-transform-runtime', { regenerator: true }], ], }, }, }, { test: /.ts$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader', ] }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: 'styles.css', }), ], };
tsconfig.json
{ "compilerOptions": { "target": "es5", "module": "es2015", "strict": true, "esModuleInterop": true, "outDir": "./dist", "sourceMap": true, "noImplicitThis": false, "removeComments": true }, "include": [ "./ts/*.ts" ], "exclude": [ "./node_modules" ] }
package.json
{ "name": "random", "version": "1.0.0", "description": "", "main": "index.ts", "scripts": { "build": "webpack --mode=development", "build:prod": "webpack --mode=production", "dev:w": "webpack --config webpack.config.js --watch" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "fast-sass-loader": "^2.0.1", "jquery": "^3.6.0", "ts-loader": "^9.4.4", "typescript": "^5.1.6", "webpack": "^5.88.1" }, "devDependencies": { "@babel/core": "^7.22.9", "@babel/preset-env": "^7.22.9", "@types/jquery": "^3.5.18", "babel-loader": "^9.1.3", "css-loader": "^6.8.1", "html-webpack-plugin": "^5.5.3", "mini-css-extract-plugin": "^2.7.6", "node-sass": "^9.0.0", "sass-loader": "^13.3.2", "style-loader": "^3.3.3", "webpack-cli": "^5.1.4", "webpack-dev-server": "^4.15.1" } }
修复方案
1. 确保TS文件以UTF-8编码保存
检查并设置编辑器将.ts文件保存为UTF-8无BOM格式,避免编码格式不一致导致的乱码。
2. 为ts-loader指定UTF-8编码
修改webpack中ts-loader的配置,添加charset: 'utf8'选项,确保loader读取文件时使用正确编码:
{ test: /.ts$/, use: { loader: 'ts-loader', options: { charset: 'utf8' } }, exclude: /node_modules/, }
3. 配置Webpack输出编码
在webpack的output选项中添加encoding: 'utf-8',强制输出文件使用UTF-8编码:
output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', encoding: 'utf-8' },
4. 补充TypeScript编码配置(可选)
在tsconfig.json的compilerOptions中添加charset: "utf-8"(TypeScript 5.0+支持),明确指定编译时的编码:
"compilerOptions": { // ...其他现有配置 "charset": "utf-8" }
验证修复
执行构建命令重新编译:
npm run build
检查dist/bundle.js中的字符是否正常显示,再打开页面验证控制台和页面文本的变音符号是否正常。
内容的提问来源于stack exchange,提问作者hencel
相关产品推荐
相关产品推荐

