Skip to content

Commit e730454

Browse files
committed
feat: locals data from script tag, close #117
1 parent d429c4a commit e730454

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

lib/index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const escapeRegexpString = require('./escape')
1010
const makeLocalsBackup = require('./backup').make
1111
const revertBackupedLocals = require('./backup').revert
1212
const placeholders = require('./placeholders')
13+
const scriptDataLocals = require('./locals')
1314

1415
const delimitersSettings = []
1516
let conditionals, switches, loops, scopes, ignored, delimitersReplace, unescapeDelimitersReplace
@@ -156,7 +157,9 @@ module.exports = function postHTMLExpressions (options) {
156157

157158
// kick off the parsing
158159
return function (tree) {
159-
return normalizeTree(clearRawTag(walk({ locals: options.locals, strictMode: options.strictMode }, tree)), tree.options)
160+
const { locals } = scriptDataLocals(tree, options)
161+
162+
return normalizeTree(clearRawTag(walk({ locals: { ...options.locals, ...locals }, strictMode: options.strictMode }, tree)), tree.options)
160163
}
161164
}
162165

lib/locals.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict'
2+
3+
const vm = require('vm')
4+
const matchHelper = require('posthtml-match-helper')
5+
const { render } = require('posthtml-render')
6+
7+
// const code = 'module.exports = {a: 1}';
8+
const ctx = vm.createContext({ module })
9+
10+
// const r = vm.runInContext(code, ctx)
11+
12+
/**
13+
* @description Get the script tag with locals attribute from a node list and return locals.
14+
*
15+
* @method scriptDataLocals
16+
*
17+
* @param {Array} tree Nodes
18+
*
19+
* @return {Object} {} Locals
20+
*/
21+
function scriptDataLocals (tree, options) {
22+
const locals = {}
23+
const localsAttr = options.localsAttr || 'locals'
24+
25+
tree.match(matchHelper(`script[${localsAttr}]`), node => {
26+
if (node.content) {
27+
const code = render(node.content)
28+
29+
try {
30+
const local = vm.runInContext(code, ctx)
31+
32+
Object.assign(locals, local)
33+
} catch {};
34+
}
35+
36+
return node
37+
})
38+
39+
return {
40+
locals
41+
}
42+
}
43+
44+
module.exports = scriptDataLocals

0 commit comments

Comments
 (0)