1. 程式人生 > 實用技巧 >Vue3.x原始碼除錯的實現方法

Vue3.x原始碼除錯的實現方法

幾句話說下我看原始碼的方式

斷點除錯

根據demo小例子或者api的使用姿勢進行除錯,每個小例子只關心其走過的邏輯分支。

如何除錯vue3.x的ts原始碼

  • 官網說使用 yarn dev 命令就可以對其進行除錯,可是執行該命令後,是生成過後的程式碼,不能對其編寫的ts原始碼進行除錯。
  • 其實再生成對應的sourcemap檔案,便可以原汁原味的除錯。
  • 先看下幾個截圖:

如果這是你想要的除錯效果,下面請看下如何生成sourcemap檔案。

生成sourcemap檔案

rollup.js中文文件

// rollup.config.js
export default {
 // 核心選項
 input,   // 必須
 external,
 plugins,

 // 額外選項
 onwarn,

 // danger zone
 acorn,
 context,
 moduleContext,
 legacy

 output: { // 必須 (如果要輸出多個,可以是一個數組)
  // 核心選項
  file,  // 必須
  format, // 必須
  name,
  globals,

  // 額外選項
  paths,
  banner,
  footer,
  intro,
  outro,
  sourcemap,
  sourcemapFile,
  interop,

  // 高危選項
  exports,
  amd,
  indent
  strict
 },
};

可以看到output物件有個sourcemap屬性,其實只要配置上這個就能生成sourcemap檔案了。 在vue-next專案中的rollup.config.js檔案中,找到createConfig函式

function createConfig(output, plugins = []) {
 const isProductionBuild =
  process.env.__DEV__ === 'false' || /\.prod\.js$/.test(output.file)
 const isGlobalBuild = /\.global(\.prod)?\.js$/.test(output.file)
 const isBunlderESMBuild = /\.esm\.js$/.test(output.file)
 const isBrowserESMBuild = /esm-browser(\.prod)?\.js$/.test(output.file)

 if (isGlobalBuild) {
  output.name = packageOptions.name
 }

 const shouldEmitDeclarations =
  process.env.TYPES != null &&
  process.env.NODE_ENV === 'production' &&
  !hasTSChecked

 const tsPlugin = ts({
  check: process.env.NODE_ENV === 'production' && !hasTSChecked,
  tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache'),
  tsconfigOverride: {
   compilerOptions: {
    declaration: shouldEmitDeclarations,
    declarationMap: shouldEmitDeclarations
   },
   exclude: ['**/__tests__']
  }
 })
 // we only need to check TS and generate declarations once for each build.
 // it also seems to run into weird issues when checking multiple times
 // during a single build.
 hasTSChecked = true

 const externals = Object.keys(aliasOptions).filter(p => p !== '@vue/shared')

 output.sourcemap = true // 這句話是新增的
 return {
  input: resolve(`src/index.ts`),
  // Global and Browser ESM builds inlines everything so that they can be
  // used alone.
  external: isGlobalBuild || isBrowserESMBuild ? [] : externals,
  plugins: [
   json({
    namedExports: false
   }),
   tsPlugin,
   aliasPlugin,
   createReplacePlugin(
    isProductionBuild,
    isBunlderESMBuild,
    isGlobalBuild || isBrowserESMBuild
   ),
   ...plugins
  ],
  output,
  onwarn: (msg, warn) => {
   if (!/Circular/.test(msg)) {
    warn(msg)
   }
  }
 }
}

加上一句output.sourcemap = true即可。 然後執行 yarn dev,可以看到vue/dist/vue.global.js.map檔案已生成。 再然後你在xxx.html通過script的方式引入vue.global.js檔案,即可除錯, 效果如上圖。

弱弱的說一句,我對ts和rollup.js不熟,幾乎陌生,但是不影響學習vue3.x原始碼。 vue3.x的原始碼這次分幾個模組編寫的,所以學習也可以分模組學習,比如學習響應式系統,執行yarn dev reactivity命令生成對應檔案,然後配合__tests__下的案列,自己進行除錯學習。(額,好像說了好幾句...)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援碼農教程。