Sto usando il webpack con HtmlWebpackPlugin, html-loadere file-loader. Ho una struttura di progetto semplice in cui non uso quadri, ma solo dattiloscritto. Pertanto, scrivo il mio codice HTML direttamente su index.html. Uso anche questo file HTML come modello in HtmlWebpackPlugin.
Come tutti i siti Web, devo inserire un'immagine che si riferisce a un file PNG nella mia cartella delle risorse. file-loadercaricare correttamente il file, inserire il nuovo nome file all'interno del srctag ma non è quello che sta succedendo. Invece, come valore del srctag, ho [object Module]. Presumo che file-loaderemetta un oggetto ed è rappresentato in questo modo quando .toString()viene eseguito il suo metodo. Tuttavia, posso vedere che file-loaderha elaborato correttamente il file ed emesso con un nuovo nome nel percorso di output. Non ricevo errori. Ecco la mia configurazione webpack e index.html.
const projectRoot = path.resolve(__dirname, '..');
{
entry: path.resolve(projectRoot, 'src', 'app.ts'),
mode: 'production',
output: {
path: path.resolve(projectRoot, 'dist'),
filename: 'app.bundle.js'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.html$/i,
use: 'html-loader'
},
{
test: /\.(eot|ttf|woff|woff2|svg|png)$/i,
use: 'file-loader'
},
{
test: /\.scss$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: false
}
},
{
loader: 'css-loader',
options: {
sourceMap: false
}
},
{
loader: 'sass-loader',
options: {
sourceMap: false
}
}
]
},
{
exclude: /node_modules/,
test: /\.ts$/,
use: 'ts-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(projectRoot, 'src', 'index.html')
}),
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
ignoreOrder: false
})
]
};
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body class="dark">
<header>
<nav class="navigation">
<div class="left">
<img src="assets/logo.png" class="logo"> <!-- This logo is output as [object Module] -->
</div>
<div class="right">
</div>
</nav>
</header>
</body>
</html>
Struttura del progetto:
config/
webpack.config.js
dist/
src/
styles/
assets/
logo.png
index.html
app.ts
Modifica le mie dipendenze package.json:
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.2.0",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.13.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"ts-loader": "^6.2.1",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"