0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

html-loaderが、インラインCSSのbackground-imageをバンドルしないのをなんとかする。

Last updated at Posted at 2022-06-22
<div class="backImage" style="background-image: url(assets/img/sample.jpg)"></div>

こんな風に書きたい。
が、ビルド時にこの画像は無視されます。

参考
https://stackoverflow.com/questions/44096749/webpack-load-images-from-inline-style-background-image
https://github.com/webpack-contrib/html-loader/pull/142

ググってみると結構問題にしてる人が多そうなのに、
これといった解決方法が見つけれなかったので、自力でなんとかしてみた。

要は、style属性の中の、urlメソッドを解析できればよいので、

--- a/node_modules/html-loader/dist/utils.js
+++ b/node_modules/html-loader/dist/utils.js
@@ -354,6 +354,12 @@ function parseSrc(input) {
     value = value.substring(0, value.length - 1);
   }
 
+  const values = value.match(/(?<=url\(['"`]?)[^'"`]+?(?=['"`]?\))/)
+  if (values) {
+    startOffset = values.index;
+    value = values[0];
+  }
+
   if (!value) {
     throw new Error("Must be non-empty");
   }

html-loderのオプションはこう

  sources: {
    list: [
      // All default supported tags and attributes
      '...',
      {
        attribute: 'style',
        type: 'src'
      }
    ]
  }

ただ、問題はリポジトリを共有するときにどうするか、
リポジトリをforkするのが一般的だが、
なるべく内々で済ませたいので、何かいいのかないのか探してたらありました。
https://bagelee.com/programming/javascript-2/patch-package/
これで、html-loaderをインストールしたタイミングでパッチがあたります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?