这是我第一次构建网络应用程序,我正处于最后的步骤中。我正在尝试将整个项目与 webpack 捆绑在一起,除了我的 SVG 图标之外,一切似乎都正常。
我认为问题在于 webpack 如何在编译的 index.html 中引用 svg。
原始index.html引用了svg,如下所示:
<svg role="img">
<use href="images/icons.svg#settings-icon"></use>
</svg>
编译后的index.html引用svg,如下所示:
<svg role="img" style="margin-bottom:-3px">
<use href="aaf2f945f2b181c45647.svg#settings-icon"></use>
</svg>
这是我编译后的 dist/ 文件夹:
dist/
├── images/
│ └── icons.svg
├── aaf2f945f2b181c45647.svg
├── bundle.js
└── index.html
aaf2f945f2b181c45647.svg包含以下内容:
export default "images/icons.svg";
icons.svg 包含了我所有的 svg。
当我在编译的index.html中将所有“aaf2f945f2b181c45647.svg”替换为“images/icons.svg”时,一切正常。问题是 webpack 似乎试图通过 aaf2f945f2b181c45647.svg 导航到 icon.svg。为什么要这样做?我可以以某种方式告诉它直接将“images/icons.svg”写入html文件吗?
这是我的
webpack.config.cjs:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: './frontend/src/scripts/index.ts', // Entry point of your application
output: {
filename: 'bundle.js', // Output bundle file name
path: path.resolve(__dirname, 'frontend/dist'), // Output directory
clean: true,
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.svg$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/',
publicPath: 'images/',
},
},
},
{
test: /\.html$/,
use: 'html-loader',
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './frontend/public/index.html', // Template HTML file
filename: 'index.html', // Output HTML file name
}),
],
};
这是我完整的文件夹结构:
dist/
├── images/
│ └── icons.svg
├── aaf2f945f2b181c45647.svg
├── bundle.js
└── index.html
public/
├── images/
│ └── icons.svg
└── index.html
src/
├── scripts/
│ └── ...
└── styles/
└── ...
我已经尝试过使用 url-loader、svg-url-loader 和 svg-sprite-loader 来代替。他们都无法显示我的 svg。