LoginSignup
14

More than 3 years have passed since last update.

TypeScript + Webpack でimport jpg

Posted at

最終的なディレクトリ構成

/src
 ┗ component 
  ┗ page
   about.tsx
 ┗ img
 ┗ page
   ┗ about
   about.jpg
 ┗ types
  import-jpg.d.ts
tsconfig.json
webpack.config.json

普通に使う

component.tsx
import image from '../../img/page/about/about.jpg'

TS2307: Cannot find module '../../img/page/about/about.jpg'.

インポートエラーになる。
理由はjpgに関する型定義が存在しないため

import errorを解消する

ルートに追加の型定義ファイルの配置ディレクトリを追加

mkdir types

型定義ファイルimport-jpg.d.tsの作成

アンビエントモジュールとして、"*.jpg"を宣言。

/types/import-jpg.d.ts
declare module "*.jpg"

型定義ファイルの読み取りをtsconfigに追加

tsconfig.json
{
  "compilerOptions": {
    "typeRoots": [
      "node_modules/@types",
      "types"
    ],
  }, 
  "include": [
    "src/**/*",
    "types/**/*"
  ]
}

この時点でインポートエラーは解消する。

ビルド向け定義

jpgファイルをwebpack対象に追加

webpack.config.json
// 他の項目は省略
    module: {
        rules: [
            {
                test: /\.(jpg|png)$/,
                loader: 'url-loader'
            }
        ]
   }

絶対パスにする

変更

tsconfig.json
{
  "compilerOptions": {
        "baseUrl": "src",
  }
}

追記

webpack.config.json
    resolve: {
        modules: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')]
    }

最終系

src配下を絶対パスでインポート可能に。

import image from 'img/page/about/about.jpg'

参考URL

TypeScript の paths はパスを解決してくれないので注意すべし!
TypeScript 画像のインポート(英語)
TypeScript2 + webpack2でのcss-loader, file-loader周辺をなんとかする

困っていること

img/でインポートできるようになったが、
結局intellijのコンテンツアシストはフォルダまでしか効かない。

一応、Ctrl+space2回で全ファイルアシストを起動して解決できるようです
が、これでは相対パスで入るため、省略パスには対応できない。

intellijには、Alt + Enter で絶対パスへの変換機能があるが、これはOSレベルの絶対パスに直されているように見える。

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
14