前端

How Smart Tools Are Shaping the Future of Creative Work

Eric Chuang
2022-03-20

因為這次的專案並不是使用 create-react-app 的做法,因此不能直接用 import {ReactComponent as Name} from '/path/to/svg';。

解決方法 1: file-loader

在 Webpack 中加入 file-loader 的載入器,讓 SVG 作為圖片載入,適用於 <img src="path/to/svg/" /> 的方式。

npm install file-loader --save-dev

接著在 webpack.config.js 中加入針對 .svg 副檔名的載入規則。

module.exports = {
/* ... */
  modules: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'images', // 我習慣會把圖片輸出到 images 這個資料夾
            }
          }
        ]
      }
    ]
  }
}

解決方法 2: @svgr/webpack

如果要使用 import {ReactComponent as Name} from '/path/to/svg'; 的方式來載入,則可以直接把 <svg> 的內容插入 HTML 中。

這種做法,適合需要透過 CSS 調整樣式的情境。

npm install @svgr/webpack --save-dev

接著在 webpack.config.js 中加入設定。

module.exports = {
/* ... */
  modules: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: '@svgr/webpack',
            options: {
              outputPath: 'images', // 我習慣會把圖片輸出到 images 這個資料夾
            }
          }
        ]
      }
    ]
  }
}

參考資料

Sign up for our newsletter

Subscribe to our newsletter to receive the latest updates, expert insights, and practical tips directly in your inbox. Stay informed with content designed to help you grow.

+480.000 happy customers

Gain more with expert solutions

Unlock the full potential of your business with our expert solutions. Our team provides tailored strategies, professional guidance, and actionable insights to help you achieve better results.

  • Eric Chuang
  • •
  • 2025-01-23
如何同時使用 Webinoly 與 Cloudflare 保護網站安全

在社群夥伴勇哥的文章〈Webinoly 最新版快速安裝〉中,提到使用 Webinoly 來建立 WordPre […]

主機