1. 程式人生 > >webpack學習(五):使用source map

webpack學習(五):使用source map

demo地址: https://github.com/Lkkkkkkg/webpack-demo
上次配置HtmlWebpackPlugin: https://blog.csdn.net/qq593249106/article/details/84901089

繼上次配置完HtmlWebpackPlugin之後, 現在開始解決追蹤警告和錯誤程式碼的原始位置問題, 先看一下當前目錄結構:

|- /dist //用於放打包後文件的資料夾
  |- app.bundle.js //出口檔案
  |- print.bundle.js //出口檔案
  |- index.html //模板檔案
|- /node_modules
|
- /src //用於放原始檔的資料夾 |- index.js //入口檔案 |- print.js //入口檔案 |- package.json |- webpack.config.js //webpack配置檔案

比如在原始檔 print.js 出現了一個錯誤, 打包之後它只會跟蹤到 bundle.js 上出現了錯誤, 對於我們找錯誤來源沒有幫助, 使用 JavaScript 自帶的 source map 功能就可以幫助追蹤錯誤的位置

配置webpack.config.js

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin =
require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: { app: './src/index.js', //多個入口檔案 print: './src/print.js' }, devtool: 'inline-source-map', // 不同選項適用於不同環境 plugins: [ //webpack 通過 plugins 實現各種功能, 比如 html-webpack-plugin 使用模版生成 html 檔案
new CleanWebpackPlugin(['dist']), //設定清除的目錄 new HtmlWebpackPlugin({ filename: 'index.html', //設定生成的HTML檔案的名稱, 支援指定子目錄,如:assets/admin.html }) ], output: { filename: '[name].bundle.js', //根據入口檔案輸出不同出口檔案 path: path.resolve(__dirname, 'dist') } };

故意生成一個錯誤

print.js

export default function printMe() {
    console.error('I get called from print.js!');
}

重新構建

終端輸入 npm run build , 開啟 index.html :
在這裡插入圖片描述
點選按鈕, 觸發事件產生錯誤, 可以看到已經準確跟蹤到了原始檔 print.js, 如果不使用 source map , 他會顯示 app.bundle.js