首页 > 解决方案 > 如何在 webpack 的对象标签中使用 svg?

问题描述

我正在尝试创建一个应用程序,该应用程序使用具有不同路径的 svg 基本图像,我需要与之交互。由于我需要访问 documentContent 中的路径,我认为通过 javascript 访问它们的最佳方式是使用 object 标记。我用inkscape创建了svg和路径。问题是我无法让 html 加载器或 svg-inline-loader 工作。html 加载器适用于所有其他标签,但不适用于对象之一。在文档中说默认属性还包括'object:data',但是,我无法让 webpack 解析 svg 图像的路径。我也尝试了文件加载器中的 svg,但没有成功。

文件夹结构:

src
| /client
| | /images
| | | image.png
| | | image.svg
| | /js
| | | app.js
| | /styles
| | | master.scss
| | /views
| | | index.html
| | index.js
| /server
| | index.js
package-lock.json
package.json
webpack.dev.js
webpack.prod.js

这是html:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86">

    <title></title>
</head>

<body>
    <section>
        <div class="container">
            <object id="svgObj" data="../images/Vista_Class.svg" type="image/svg+xml" class="base-img">
                <!-- Fall back message -->
                Your browser doesn't support SVG. Try opening with Chrome.
                <img src="../images/Vista_Class.png" alt="ship profile" class="base-img">
            </object>
        </div>

    </section>

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

</body>

</html>

客户端 app.js 文件中 svg 上的简单测试事件监听器

const view = {
    /**
     * @param {string} objId id of the svg image for the base ship image. The
     *                       id passed to this function should be the one in
     *                       the svg xml file.
     */
    init: (objId) => {
        // Wait until the DOM is fully loaded before initializing the view
        document.addEventListener('DOMContentLoaded', () => {
            const svgObj = document.getElementById(objId)
            const svgDoc = svgObj.contentDocument
            const paths = svgDoc.querySelectorAll('path')
            console.log(paths)
            svgDoc.addEventListener('click', function (event){
                event.preventDefault()
                console.log('clicked')
            })
        })
    },
}

我的 Webpack 开发配置:

const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
    entry: './src/client/index.js',
    mode: 'development',
    devtool: 'source-map',
    stats: 'verbose',
    output: {
        libraryTarget: 'var',
        library: 'Client'
    },
    module: {
        rules: [
            {
                test: '/\.js$/',
                exclude: /node_modules/,
                loader: "babel-loader"
            },
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            },
            {
                test: /\.(png|jp(e*)g$)/,  
                use: [{
                    loader: 'file-loader',
                    options: { 
                        //limit: 8000, // Convert images < 8kb to base64 strings
                        name: '[hash]-[name].[ext]',
                        outputPath: 'images/',
                        publicPath: 'images/',
                        esModule: false
                    } 
                }]
            },
            { 
                test: /\.svg$/, 
                loader: 'svg-inline-loader' 
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },

        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: "./src/client/views/index.html",
            filename: "./index.html",
        }),
        new CleanWebpackPlugin({
            // Simulate the removal of files
            dry: true,
            // Write Logs to Console
            verbose: true,
            // Automatically remove all unused webpack assets on rebuild
            cleanStaleWebpackAssets: true,
            protectWebpackAssets: false
        })
    ],
    devServer: {
        historyApiFallback: true
    }
}

非常感谢您的帮助。

标签: javascriptsvgwebpack

解决方案


推荐阅读