[Note] webpack 5 problem: Refused to execute script because its MIME type ('text/html') is not executable


Posted by urlun0404 on 2022-11-15

處理"cannot GET/xxx"的筆記提到 publicPath: "/" 這個組態,webpack在官方文件有說這是非常重要的設定:

This is an important option when using on-demand-loading or loading external resources like images, files, etc.

我是在用React-Router設定巢狀路由(nested routes),遇到這個問題,當時給出像下面這樣子的錯誤訊息:

GET http://localhost:8080/bundle.js net::ERR_ABORTED
Refused to execute script from 'http://localhost:8080/bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

一開始看到錯誤訊息還以為是React-Router設定巢狀路由的問題,翻遍一堆文章無果😢 甚至還有網友在問有人解決這個問題了嗎???。


output: { publicPath: "/" }

後來想到可能也是webpack server處理路徑請求給出的訊息,改用webpack關鍵字搜尋找到這篇問答,簡單來說,這位網友回答webpack基本設定無法處理過於複雜的路由,所以要自己去加上一些設定。

這次是要在webpack.config檔案組態設定的 output 加上 publicPath,至於後面的 "/" 要視專案而定,不一定要設定成 /

module.exports = {
  //...
  output: {
    publicPath: "/",
  },
};


根據官方文件的說明:

This option specifies the public URL of the output directory when referenced in a browser. A relative URL is resolved relative to the HTML page (or tag).

因為錯誤訊息是說找不到bundle.js檔案,我的bundle.js檔案是跟index.html文件放在根路徑,所以設定成 output: { publicPath: "/" }

總之在用React-Router-Dom處理比較複雜的路由時,要多注意server方處理路徑的設定。




#Webpack #webpack5 #problem #note #route #router #react-router-dom







Related Posts

Call by Reference & Call by Sharing

Call by Reference & Call by Sharing

C++筆記 將函式當作參數傳遞

C++筆記 將函式當作參數傳遞

CSS單位大全 (px,em,rem,vh,vw,vmin,vmax)

CSS單位大全 (px,em,rem,vh,vw,vmin,vmax)


Comments