我将 webpack 与HtmlWebpackPlugin
,html-loader
和file-loader
. 我有一个简单的项目结构,其中我不使用框架,而只使用typescript。因此,我将我的 HTML 代码直接写入index.html
. 我也使用这个 HTML 文件作为我的模板HtmlWebpackPlugin
。
与所有网站一样,我需要在我的资产文件夹中放置一个引用 PNG 的图像。file-loader
应该正确加载文件,将新文件名放入src
标签中,但这不是正在发生的事情。相反,作为src
标签的值,我有[object Module]
. 我假设它file-loader
发出一些对象,并且在.toString()
运行它的方法时它是这样表示的。但是,我可以看到file-loader
已成功处理文件并以新名称发送到输出路径。我没有错误。这是我的 webpack 配置和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
})
]
};
索引.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>
项目结构:
config/
webpack.config.js
dist/
src/
styles/
assets/
logo.png
index.html
app.ts
编辑 我的 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"