I have a simple website built using Node.js and TypeScript, which is prepared for distribution through webpack. When I open the output in browser, it works just fine. However, if I open the page using lite-server and browser-sync, I get an odd error – the script is run twice and odd HTML is interjected.
Relevant part of index.html; JS console gives back error “404 file not found”.
<head>
<script type = "module" src="scripts.js"></script>
</head>
<body>
<div class="logo-container">
/*The upper <img>-tag is the wrong one, the lower one loads just fine.
<img src="https://localhost:3000/browser-sync/images/287cb8e0d137623f010f.png">
<img src="https://localhost:3000/images/287cb8e0d137623f010f.png">
</div>
</body>
...
In addition console shows that the script is ran twice, first with the prefix VM11.
Relevant part of scripts.ts
import $ from 'jquery';
import logoImage from './img/logo.png';
import logoMedicine from './img/medicine.png';
$(function(){
document.getElementsByClassName('logo-container')[0]?.appendChild(imgElement);
document.getElementById('rx_img')?.appendChild(medicineImage);
});
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/scripts.ts',
module: {
rules: [
{
test: /.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
generator: {
filename: 'images/[hash][ext][query]'},
},
{
test: /.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'scripts.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
};
tsconfig.js
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es6",
"target": "es6",
"allowJs": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
},
"include": [
"src",
"index.d.ts"
],
"exclude": [
"node_modules"
],
}
package.json
{
"name": "test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "lite-server --baseDir="./dist"",
"build": "webpack"
},
"dependencies": {
"@types/node": "^20.14.11",
"bootstrap": "^5.3.*",
"jquery": "^3.7.1"
},
"devDependencies": {
"@types/jquery": "^3.5.30",
"css-loader": "^7.1.2",
"file-loader": "^6.2.0",
"html-loader": "^5.0.0",
"html-webpack-plugin": "^5.6.0",
"style-loader": "^4.0.0",
"ts-loader": "^9.5.1",
"typescript": "^5.5.3",
"webpack": "^5.93.0",
"webpack-cli": "^5.1.4"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}