Skip to content

Commit

Permalink
fix(core): add caching to webRequire (#971)
Browse files Browse the repository at this point in the history
  • Loading branch information
hrgdavor authored Jan 23, 2022
1 parent bd82558 commit 9095129
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 3 additions & 1 deletion packages/core/src/code-loading/webRequire.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const makeWebRequire = (filesAndFolders, options) => {
// console.log('*****\n',filesAndFolders,'\n*****')

const extensions = {}
const moduleCache = {}

/* Require (obtain) the exports for the given require path, relative to the given current path.
* The logic is based on the original NODE require() function.
Expand Down Expand Up @@ -105,6 +106,7 @@ const makeWebRequire = (filesAndFolders, options) => {
if (entry.children) return null // directory

if (extensions[baseExt]) {
if(moduleCache[requirePath]) return moduleCache[requirePath]
// evaluate the content
const matchingModule = {
exports: {},
Expand All @@ -121,7 +123,7 @@ const makeWebRequire = (filesAndFolders, options) => {
}
}
extensions[baseExt](matchingModule, entry.fullPath)
return matchingModule.exports
return moduleCache[requirePath] = matchingModule.exports
}
return null
}
Expand Down
5 changes: 4 additions & 1 deletion packages/core/src/code-loading/webRequire.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ test('webRequire: should support require, from a single file', (t) => {

let requireFn = makeWebRequire(singleFileJs, { apiMainPath })
let designRootModule = requireFn(singleFileJs[0].fullPath)
const designRootModule2 = requireFn(singleFileJs[0].fullPath)

t.true('main' in designRootModule)
t.true(designRootModule.main instanceof Function)

t.is(designRootModule, designRootModule2)
t.deepEqual(designRootModule, designRootModule2)

// NOTE: 'jscad' must be registered as an extension
const fakeFs = makeFakeFs(singleFileJscad)
requireFn = makeWebRequire(singleFileJscad, { apiMainPath })
Expand All @@ -32,7 +36,6 @@ test('webRequire: should support require, from a directory with index.js', (t) =

const requireFn = makeWebRequire(directoryWithIndexJs, { apiMainPath })
const designRootModule = requireFn('/project')

t.true('main' in designRootModule)
t.true(designRootModule.main instanceof Function)
})
Expand Down

0 comments on commit 9095129

Please sign in to comment.