Я пытаюсь создать приложение, которое использует базовый образ SVG с разными путями, с которыми мне нужно взаимодействовать. Поскольку мне нужно получить доступ к путям в documentContent, я думаю, что лучший способ получить к ним доступ через javascript - это использовать тег объекта. Я создал SVG и пути с Inkscape. Проблема в том, что я не могу заставить работать загрузчик html или svg-inline-loader. Загрузчик html работает со всеми другими тегами, но не с объектным. В документации говорится, что атрибуты по умолчанию включают также 'object: data' , однако я не могу получить веб-пакет для разрешения пути к изображению 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>
Простое событие тестирования слушатель на svg в клиентском приложении. js файл
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')
})
})
},
}
Моя dev-конфигурация 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
}
}
Большое спасибо за помощь.