LoginSignup
0
0

Parcel で静的ファイルの URL を取得する

Last updated at Posted at 2023-10-22

例えば Parcel で画像ファイルの URL が欲しい場合は、単に import するだけで手に入ります。

Image.tsx
import image from "path/to/image.png";

export function Logo() {
  return <img src={image} />;
}

ただし CSS や JSON の場合、単に import すると URL ではなくオブジェクトが手に入ってしまいます。

Stylesheet.tsx
import stylesheet from "path/to/index.css"; // CSS Modules として import されてしまう

export function Stylesheet() {
  return <link rel="stylesheet" href={stylesheet} />; // これは動かない
}

Parcel 2 に搭載されている url: パターンを用いることで、URL を取得することができます。

Stylesheet.tsx
import stylesheet from "url:path/to/index.css";

export function Stylesheet() {
  return <link rel="stylesheet" href={stylesheet} />;
}

For the current version of parcel 2 I'm using (^2.0.0-alpha.3.2), the url:path pattern is default behaviour.

ちなみにそのままだと TypeScript がエラーを吐くので、アンビエントモジュール宣言を追加する必要があります。

types/declaration.d.ts
declare module "url:*" {
  const url: string;
  export default url;
}

CSS ファイルの URL が欲しいケースは稀ですが、例えば React を使って Web Components のカスタム要素を作成する場合などで、このテクニックが必要になることがあります。

誰かの参考になれば幸いです。
(もっと良いやり方をご存知の方がいれば、コメントにてお教えください。)

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