While working on my project, I encountered an issue with diacritics marks (such as German or Polish characters) when using Webpack with Typescript. Unfortunately, the problem arises when trying to display these marks in the console or on a webpage. It seems that the issue is related to either webpack, ts-loader, or Typescript.
The problem does not occur when adding these diacritic marks through a simple JavaScript file. The UTF-8 encoding is present in the meta tag.
For instance:
From a TypeScript file:
console.log('ü, ö, ä ą, ś, ć, ł')
From a webpage: https://i.sstatic.net/MD0NA.png
After translating by webpack in bundle.js: console.log(', , , , , ');
The same issue occurs when attempting to display text on a webpage.
Here is the Webpack configuration:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
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',
}),
],
};
Typescript configuration (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"
}
}