Skip to content
This repository was archived by the owner on Aug 16, 2022. It is now read-only.

Commit 833605d

Browse files
authored
feat: transform require to import statements in esModule (#54)
1 parent 7024fb8 commit 833605d

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

src/assemble.js

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,25 @@ function inlineStyle (name, style, config) {
2626
return output
2727
}
2828

29+
function inlineTemplate (render, config) {
30+
const lines = render.code.split('\n')
31+
let i = 0
32+
while (lines[i].startsWith('import ')) {
33+
i += 1
34+
}
35+
36+
const imports = lines.slice(0, i).join('\n')
37+
const code = lines.slice(i).join('\n')
38+
39+
return (
40+
`\n/* template */\n` +
41+
imports + '\n' +
42+
`var __vue_template__ = (function () {\n${pad(
43+
code.replace(EXPORT_REGEX, 'return ').trim()
44+
)}})()\n`
45+
)
46+
}
47+
2948
const Source = struct({
3049
script: {
3150
id: struct.union(['string?', 'null']),
@@ -184,11 +203,7 @@ module.exports = function assemble (source, filename, config) {
184203

185204
// <template>
186205
if (typeof render.code === 'string') {
187-
output +=
188-
`\n/* template */\n` +
189-
`var __vue_template__ = (function () {\n${pad(
190-
render.code.replace(EXPORT_REGEX, 'return ').trim()
191-
)}})()\n`
206+
output += inlineTemplate(render, config)
192207
} else {
193208
output += importStatement(render.id, {
194209
esModule: config.esModule,

src/template-compiler/index.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,22 @@ module.exports = function compileTemplate (template, filename, config) {
102102
output.code += `\nmodule.exports = ${__exports__}`
103103
} else {
104104
output.code += `\nexport default ${__exports__}`
105+
106+
// remove all require statements
107+
const imports = []
108+
output.code = output.code.replace(/\brequire\("([^"]+)"\)/g, (_, name) => {
109+
let index = imports.indexOf(name)
110+
if (index === -1) {
111+
index = imports.length
112+
imports.push(name)
113+
}
114+
const ref = `__vue_template_import_${index}__`
115+
116+
return ref
117+
})
118+
output.code =
119+
imports.map((name, i) => `import __vue_template_import_${i}__ from '${name}'`).join('\n') +
120+
'\n\n' + output.code
105121
}
106122

107123
return output

0 commit comments

Comments
 (0)