简体   繁体   中英

Copy images in html files to output directory with webpack

I am trying to configure webpack so it parses my index.html (ideally with HTMLWebpack Plugin), so that any included image (eg <object data="images/test.svg"> ) is moved to my output folder, with the folder path remaining the same. Ultimately, running webpack-dev-server should render a page that displays my images.

This question is somewhat related, but doesn't quite match my own problem.

What I tried to do:

As you can see from my config file, I tried using the html-loader . Without the exclude: /index\\.html$/ it gives me an error. My guess is that the HTMLWebpack Plugin and the html-loader don't get along. Excluding index.html defeats the purpose of html-loader. File-loader doesn't recognize images that aren't included using require(image) .

What is currently happening: Everything runs fine, but there's no images folder, nor any image in /dist/ .

My current webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});

module.exports = {
entry: './app/index.js',

output: {
    path: __dirname + '/dist',
    publicPath: '/dist',
    filename: 'index_bundle.js'
},

module: {
    loaders: [
    { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
    { test: /\.svg$/, loader: 'file-loader' },
    { test: /\.html$/, exclude: /index\.html$/, loader: 'html-loader'}
    ]
},

plugins: [
    HTMLWebpackPluginConfig
]
}

Example index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <div id="demoSpace"><object data="images/test.svg"  type="image/svg+xml"></object></div>
    <div id="test"></div> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js">      
    </script>
</body>
</html>

My take on what I see in the html-loader documentation is that it will default to automatically require ing what it finds in "img" tags. Since you're dealing with an "object" tag you probably want to focus on the tag-attribute processing feature discussed:

You can specify which tag-attribute combination should be processed by this loader via the query parameter attrs. Pass an array or a space-separated list of : combinations. (Default: attrs=img:src)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM