從現有原始碼檔案(從其 sourceMappingURL
)中萃取原始碼對應。
首先,您需要安裝 source-map-loader
npm i -D source-map-loader
或
yarn add -D source-map-loader
或
pnpm add -D source-map-loader
然後將外掛程式新增至您的 webpack
設定檔。例如
file.js
import css from "file.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
],
},
};
source-map-loader
會從所有 JavaScript 條目中擷取現有的原始碼對應。這包括內嵌原始碼對應以及透過 URL 連結的原始碼對應。所有原始碼對應資料都會傳遞給 webpack 進行處理,依照 原始碼對應樣式 所選定的方式處理,而該樣式則由 webpack.config.js 中的 devtool
選項指定。當使用具有自己原始碼對應的第三方程式庫時,這個 loader 特別有用。如果未擷取並處理成 webpack 捆綁的原始碼對應,瀏覽器可能會誤解原始碼對應資料。source-map-loader
允許 webpack 在程式庫之間維持原始碼對應資料的連續性,因此可以輕鬆進行除錯。source-map-loader
會從任何 JavaScript 檔案中擷取,包括 node_modules
目錄中的檔案。設定 include 和 exclude 規則條件時,請務必謹慎,以最大化捆綁效能。
然後透過您偏好的方法執行 webpack
。
名稱 | 類型 | 預設值 | 說明 |
---|---|---|---|
filterSourceMappingUrl | {Function} | undefined | 允許控制 SourceMappingURL 行為 |
類型:Function
預設值:undefined
允許您指定 loader 對 SourceMappingURL
註解的行為。
函式必須傳回以下其中一個值
true
或 'consume'
- 使用原始碼對應並移除 SourceMappingURL
註解(預設行為)false
或 'remove'
- 不使用來源地圖並移除 SourceMappingURL
註解skip
- 不使用來源地圖且不移除 SourceMappingURL
註解範例設定
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: [
{
loader: "source-map-loader",
options: {
filterSourceMappingUrl: (url, resourcePath) => {
if (/broker-source-map-url\.js$/i.test(url)) {
return false;
}
if (/keep-source-mapping-url\.js$/i.test(resourcePath)) {
return "skip";
}
return true;
},
},
},
],
},
],
},
};
若要忽略警告,可以使用下列設定
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
],
},
ignoreWarnings: [/Failed to parse source map/],
};
關於 ignoreWarnings
選項的更多資訊,請參閱此處
如果您尚未閱讀我們的貢獻指南,請花點時間閱讀。