Skip to content

Как заменить подстроку в строке в файле HTML в Webpack 5 #82

Description

@sergeysnz

Здравствуйте Валентин,
Решил попробовать ваш лоадер, но столкнулся с проблемой.
Пусть у нас в HTML файле есть строка с псевдонимом <img src="@img/logo.jpg" alt="">
Я хочу псевдоним @img/ заменить на реальный путь, например img/
В конфигурационном файле webpack.config.js прописал следующее:

module: {
        rules: [
            {
                test: /\.html$/i,
                loader: 'string-replace-loader',
                options: {
                    search: /@img\//g,
                    replace: 'img/',
                    strict: true
                }
            },
          ]
   }

после команды npm run build (webpack --node-env=production)
в консоли появляется строка

[info] Working on 1 .html files (это после того как я прописал strict: true)
(node:8336) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
(Use "node --trace-deprecation ..." to show where the warning was created)
...
./src/img/logo.jpg 42 bytes (javascript) 154 KiB (asset) [built] [code generated]

Но как видно Webpack выгрузил изображение из html файла.

Если убрать правило string-replace-loader из модулей конфига, то получаю ошибку

ERROR in ./src/index.html 3:33-76
Module not found: Error: Can't resolve './@img/logo.jpg' in 'D:\Web\template\WebpackTemplate\src'
resolve './@img/logo.jpg' in 'D:\Web\template\WebpackTemplate\src'
  using description file: D:\Web\template\WebpackTemplate\package.json (relative path: ./src)
    using description file: D:\Web\template\WebpackTemplate\package.json (relative path: ./src/@img/logo.jpg)
      no extension
        D:\Web\template\WebpackTemplate\src\@img\logo.jpg doesn't exist
      as directory
        D:\Web\template\WebpackTemplate\src\@img\logo.jpg doesn't exist
 @ ./src/index.js 1:0-22

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions