瀏覽代碼

feat(compiler-sfc): add cache for parsing sfc (#453)

QuincyChen 6 年之前
父節點
當前提交
4e538ac465
共有 3 個文件被更改,包括 17 次插入2 次删除
  1. 3 0
      packages/compiler-sfc/package.json
  2. 9 2
      packages/compiler-sfc/src/parse.ts
  3. 5 0
      yarn.lock

+ 3 - 0
packages/compiler-sfc/package.json

@@ -35,5 +35,8 @@
     "postcss": "^7.0.21",
     "postcss-selector-parser": "^6.0.2",
     "source-map": "^0.7.3"
+  },
+  "devDependencies": {
+    "@types/lru-cache": "^5.1.0"
   }
 }

+ 9 - 2
packages/compiler-sfc/src/parse.ts

@@ -7,6 +7,7 @@ import {
   SourceLocation
 } from '@vue/compiler-core'
 import { RawSourceMap } from 'source-map'
+import LRUCache from 'lru-cache'
 import { generateCodeFrame } from '@vue/shared'
 
 export interface SFCParseOptions {
@@ -48,6 +49,8 @@ export interface SFCDescriptor {
   customBlocks: SFCBlock[]
 }
 
+const SFC_CACHE_MAX_SIZE = 500
+const sourceToSFC = new LRUCache<string, SFCDescriptor>(SFC_CACHE_MAX_SIZE)
 export function parse(
   source: string,
   {
@@ -56,7 +59,11 @@ export function parse(
     sourceRoot = ''
   }: SFCParseOptions = {}
 ): SFCDescriptor {
-  // TODO check cache
+  const sourceKey = source + needMap + filename + sourceRoot
+  const cache = sourceToSFC.get(sourceKey)
+  if (cache) {
+    return cache
+  }
 
   const sfc: SFCDescriptor = {
     filename,
@@ -101,7 +108,7 @@ export function parse(
   if (needMap) {
     // TODO source map
   }
-  // TODO set cache
+  sourceToSFC.set(sourceKey, sfc)
 
   return sfc
 }

+ 5 - 0
yarn.lock

@@ -1253,6 +1253,11 @@
   dependencies:
     jest-diff "^24.3.0"
 
+"@types/lru-cache@^5.1.0":
+  version "5.1.0"
+  resolved "https://registry.yarnpkg.com/@types/lru-cache/-/lru-cache-5.1.0.tgz#57f228f2b80c046b4a1bd5cac031f81f207f4f03"
+  integrity sha512-RaE0B+14ToE4l6UqdarKPnXwVDuigfFv+5j9Dze/Nqr23yyuqdNvzcZi3xB+3Agvi5R4EOgAksfv3lXX4vBt9w==
+
 "@types/minimatch@*":
   version "3.0.3"
   resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d"