Webpack is not copying images to dist folder

拥有回忆 提交于 2019-12-01 03:51:24

问题


I'm starting with webpack, but I'm really new on this and I'm stuck right now. My project copies my fonts correctly but not images. Now the only way I am able to make it work is by copying my images manually to the dist/img folder.

This is my config:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require('webpack');
var path = require("path");



module.exports = {
entry: './src/app.js',
output: {
    path: path.resolve(__dirname + '/dist'),
    filename: 'app.bundle.js'
    // publicPath:  '/dist',
},
module: {
    rules:[
        {
        test:/\.scss$/,
        use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: ["css-loader?sourceMap","resolve-url-loader","sass-loader?sourceMap"],
            // publicPath: '/dist'
            })
        },
        {
            test: /\.(woff2?|ttf|otf|eot|svg)$/,
            use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'fonts/'
                    }  
                  }]
            // loader: 'file-loader?name=/fonts/[name].[ext]'
        },
        {
            test: /\.(jpg|png|gif)$/,
            use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'img/',
                        publicPath:'img/'
                    }  
                  }]
        }
    ]
},
devServer: {
    contentBase: path.join(__dirname, "/dist"),
    compress: true,
    port: 8000,
    stats: "errors-only",
    open: true
},
plugins: [
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    new ExtractTextPlugin("styles.css"),
    new HtmlWebpackPlugin({
        title: 'Project',
        hash:true,
        template: './src/index.html'
    })
]
}

I've tried several configurations but no solution. I also searched here for any solution but without success.

Sorry for my English.

Here is my structure: Structure from my sublime text

Thanks for all!!


回答1:


If your images are only referenced in HTML files as <img> tags, webpack by default won't pick them up because it doesn't parse HTML. You have at least 2 choices:

  1. Use CopyWebpackPlugin to copy the files to wherever you want, this at least removes the "manual" part you mention

  2. Move your images references to styles, where webpack can pick them up via the scss loader you are using. For example

    background-image: url("img/foo.png");
    


来源:https://stackoverflow.com/questions/48704770/webpack-is-not-copying-images-to-dist-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!