изображения не загружаются в html с использованием webpack - PullRequest
0 голосов
/ 04 августа 2020

У меня возникли проблемы с загрузкой изображений из папки, отличной от папки, в которой находится мой файл index. html. Ниже показано сообщение, которое я получаю с консоли.

GET http://localhost:3000/company-logo.jpg 404 (Not Found)

Вот мой каталог файлов

enter image description here

webpack.config.js

const currentTask = process.env.npm_lifecycle_event
const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const fse = require('fs-extra')

const postCSSPlugins = [
    require('postcss-import'),
    require('postcss-simple-vars'),
    require('postcss-nested'),
    require('autoprefixer')
]

class RunAfterComile {
    apply(compiler) {
        compiler.hooks.done.tap('Copy images', function() {
            fse.copySync('./public/images', './dist/public/images')
        })
    }
}

let cssConfig = {
    test: /\.css$/i,
    use: ['css-loader?url=false', {loader: 'postcss-loader', options: {plugins: postCSSPlugins}}]
}

let pages = fse.readdirSync('./views').filter(function(file) {
    return file.endsWith('.html')
}).map(function(page) {
    return new HtmlWebpackPlugin({
        filename: page,
        template: `./views/${page}`
    })
})

let config = {
    entry: './public/scripts/App.js',
    plugins: pages,
    module: {
        rules: [
            cssConfig
        ]
    }
}

if (currentTask == 'dev') {
    cssConfig.use.unshift('style-loader')
    config.output = {
        filename: 'bundled.js',
        path: path.resolve(__dirname, 'public')
    }
    config.devServer = {
        before: function(app, server) {
            server._watch('./views/**/*.html')
        },
        contentBase: path.join(__dirname, './views'),
        hot: true,
        port: 3000
    }
    config.mode = 'development'
}

if (currentTask == 'build') {
    config.module.rules.push({
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env']
            }
        }
    })
    cssConfig.use.unshift(MiniCssExtractPlugin.loader)
    postCSSPlugins.push(require('cssnano'))
    config.output = {
        filename: '[name].[chunkhash].js',
        chunkFilename: '[name].[chunkhash].js',
        path: path.resolve(__dirname, 'dist')
    }
    config.mode = 'production'
    config.optimization = {
        splitChunks: {chunks: 'all'}
    }
    config.plugins.push(
        new CleanWebpackPlugin(), 
        new MiniCssExtractPlugin({filename: 'styles.[chunkhash].css'}),
        new RunAfterComile()
        )
}

module.exports = config

The css works perfectly fine. I seem to only be having problems with images.

I tried the following file paths but they didn't work. I think I am missing something.

index.html

  1. dfgadfg
  2. <img src="../public/images/company-logo.jpg" alt="dfgadfg">
  3. <img src="./images/company-logo.jpg" alt="dfgadfg">

любая помощь приветствуется. Большое спасибо.

Ответы [ 2 ]

0 голосов
/ 04 августа 2020

Вам может потребоваться файловый загрузчик для правильного обслуживания изображений

rules: [
  {
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
      outputPath: 'images' // Chage this like 'public/images' or any other relative path to the root
    }
  },
  ...
]

Попробуйте проверить и проверить, как изображения загружаются на вкладке Source в Developer Инструменты , измените outputPath соответственно.

Обновить

Если изображения по-прежнему не загружаются на вкладку Source браузера, попробуйте импортировать их в свой App.js (точка входа файл)

....
import "../public/images/company-logo.jpg";

...
0 голосов
/ 04 августа 2020

Попробуйте использовать

module: {
      rules: [
       {
         test: /\.(png|svg|jpg|gif)$/,
         use: [
           'file-loader',
         ],
       },
      ],
    },
...