tags : HTML, JavaScript, TypeScript, React, webpack, Next.js, Storybook

Next.js, Storybook, TypeScript で html ファイルを string として読み込む

html-loader をインストール

最新のものはstorybookでエラーになるので、1.3.0 をインストール

yarn add -D html-loader@1.3.0

next.js の設定

next.config.js に書きを追加

webpack: (config, options) => {
  config.module.rules.push({
    test: /\.(html)$/,
    exclude: /node_modules/,
    use: {
      loader: 'html-loader',
    },
  })
  return config

全体例

/** @type {import('next').NextConfig} */
module.exports = {
  reactStrictMode: true,
  basePath: process.env.BASE_PATH || '',
  eslint: {
    ignoreDuringBuilds: true,
  },
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.(html)$/,
      exclude: /node_modules/,
      use: {
        loader: 'html-loader',
      },
    })
    return config
  },
}

typescript の設定

import で読み込んだ html の型が不明でエラーになる問題の解決法

tsconfig.json に下記を追加

"include": ["types/*.d.ts"],

全体例

"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "types/*.d.ts"],

/types/html.d.ts を作成し下記を記述

declare module '*.html' {
  const value: string
  export default value
}

storybook の設定

.storybook/main.js に下記を追加

config.module.rules.push(
  // HTMLを読み込ませたい
  {
    test: /\.html$/,
    use: ['html-loader'],
    include: path.resolve(__dirname, '../'),
  },
)

eslint で any になる

include を上書きしていて html.d.ts を読み込んでいないため

tsconfig.eslint.json を下記に修正

{
  "extends": "./tsconfig.json",
  "include": [
    "src/**/*.js",
    "src/**/*.jsx",
    "src/**/*.ts",
    "src/**/*.tsx",
    "pages/**/*.jsx",
    "pages/**/*.tsx",
    "types/*.d.ts"
  ],
  "exclude": ["node_modules"]
}