@ludovikxlv
На пути обучения

В чем ошибка webpack?

**Ошибка возникает при подключении картинки через img в html. При подключении через beckground, все работает.**

**Ошибка:**
ERROR in   Error: C:\Users\wsss\Desktop\webpack-main\src/index.html?../node_modules/html-webpack-plugin/lib/loader.js:9
      var ___HTML_LOADER_IMPORT_0___ = new URL(/* asset import */ __webpack_require__(/*! ./img/img.jpg */ "./img/img.jpg"), __webpack_require__.b);
                                       ^
      ReferenceError: URL is not defined
    
      - loader.js:9 eval
        [index.html?..]/[html-webpack-plugin]/lib/loader.js:9:34
    
      - index.html:40 Object.../node_modules/html-webpack-plugin/lib/loader.js!./index.html
        C:/Users/wsss/Desktop/webpack-main/src/index.html:40:1
    
      - index.html:73 __webpack_require__
        C:/Users/wsss/Desktop/webpack-main/src/index.html:73:41
    
      - index.html:131
        C:/Users/wsss/Desktop/webpack-main/src/index.html:131:37
    
      - index.html:134
        C:/Users/wsss/Desktop/webpack-main/src/index.html:134:12
    
      - node:vm:143 Script.runInContext
        node:vm:143:18
    
      - index.js:136 HtmlWebpackPlugin.evaluateCompilationResult
        [webpack-main]/[html-webpack-plugin]/index.js:136:28
    
      - index.js:333
        [webpack-main]/[html-webpack-plugin]/index.js:333:26
    
      - async Promise.all
    
      - async Promise.all
    
    
    
    webpack 5.23.0 compiled with 1 error in 610 ms
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! webpack-main@1.0.0 dev: `cross-env NODE_ENV=development webpack --mode development`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the webpack-main@1.0.0 dev script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\wsss\AppData\Roaming\npm-cache\_logs\2021-02-18T23_54_12_036Z-debug.log


**файл webpack.config**

const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    // const { Template } = require('webpack');
    const {CleanWebpackPlugin} = require('clean-webpack-plugin');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    
    const isDev = process.env.NODE_ENV === 'development';
    const isProd = !isDev;
    
    const filename = ext => isDev ? `[name].${ext}` : `[name].[contenthash].${ext}`
    module.exports = {
        context: path.resolve(__dirname,'src'),
        mode: 'development',
      entry: {
          main: './index.js',
          analytics: './analytics.js',
          bundle: [
            "webpack/hot/dev-server",
            (`${__dirname}/src/index.js`)
          ]
      },
        
      output: {
        filename: `./js/${filename('js')}`,
        path: path.resolve(__dirname,path.basename(__dirname)),
        // publicPath: '',
      },
      devServer: {
        historyApiFallback: true,
        contentBase: path.resolve(__dirname, path.basename(__dirname)),
        open: true,
        compress: true,
        hot: true,
        port: 3000,
      },
      plugins: [
          new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'src/index.html'),
            filename: 'index.html',
            minify: {
              collapseWhitespace: isProd
            }
          }),
          new CleanWebpackPlugin(),
          new MiniCssExtractPlugin({
              filename: `./styles/${filename('css')}`,
          }),
          new CopyWebpackPlugin({
            patterns: [
              {from: path.resolve(__dirname, 'src/assets') , to: path.resolve(__dirname, path.basename(__dirname))}
            ]
          }),
      ],
      module: {
          rules: [
              {
                  test: /\.html$/,
                  loader: 'html-loader'
              },
              {
                test: /\.css$/i,
                 use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                          hmr: isDev
                        },
                      },
                      'css-loader'
                  ],
              },
              {
                test: /\.s[ac]ss$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                          publicPath: (resourcePath, context) => {
                            return path.relative(path.dirname(resourcePath), context) + '/';
                          },
                        }
                      },
                      'css-loader',
                      'sass-loader'
                ]
              },
              {
                test: /\.(?:|gif|png|jpg|jpeg|svg)$/,
                use: [{
                  loader: 'file-loader',
                  options: {
                    name: `./img/${filename('[ext]')}`
                  }
                }],
              },
          ]
      }
    }


**файл package.json**

{
      "name": "webpack-main",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "test",
        "build": "cross-env NODE_ENV=production webpack --mode production",
        "dev": "cross-env NODE_ENV=development webpack --mode development",
        "start": "cross-env NODE_ENV=development webpack serve --mode development"
      },
      "keywords": [
        "webpack",
        "js"
      ],
      "author": "Kochanov Andrei",
      "license": "MIT",
      "devDependencies": {
        "clean-webpack-plugin": "^3.0.0",
        "copy-webpack-plugin": "^7.0.0",
        "cross-env": "^7.0.3",
        "css-loader": "^5.0.2",
        "file-loader": "^6.2.0",
        "html-loader": "^2.0.0",
        "html-webpack-plugin": "^5.1.0",
        "mini-css-extract-plugin": "^1.3.8",
        "node-sass": "^5.0.0",
        "path": "^0.12.7",
        "sass-loader": "^11.0.1",
        "style-loader": "^2.0.0",
        "webpack": "^5.23.0",
        "webpack-cli": "^4.5.0",
        "webpack-dev-server": "^3.11.2"
      }
    }
  • Вопрос задан
  • 68 просмотров
Решения вопроса 1
@ludovikxlv Автор вопроса
На пути обучения
Решил!

{
              test: /\.html$/,
              loader: 'html-loader',
              options: {
              esModule: false
            }
          },
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы