UNPKG

2.63 kBJavaScriptView Raw
1import * as runtimeDom from '@vue/runtime-dom';
2import { initCustomFormatter, warn, registerRuntimeCompiler } from '@vue/runtime-dom';
3export * from '@vue/runtime-dom';
4import { compile } from '@vue/compiler-dom';
5import { isString, NOOP, extend, generateCodeFrame } from '@vue/shared';
6
7function initDev() {
8 {
9 initCustomFormatter();
10 }
11}
12
13// This entry is the "full-build" that includes both the runtime
14if ((process.env.NODE_ENV !== 'production')) {
15 initDev();
16}
17const compileCache = Object.create(null);
18function compileToFunction(template, options) {
19 if (!isString(template)) {
20 if (template.nodeType) {
21 template = template.innerHTML;
22 }
23 else {
24 (process.env.NODE_ENV !== 'production') && warn(`invalid template option: `, template);
25 return NOOP;
26 }
27 }
28 const key = template;
29 const cached = compileCache[key];
30 if (cached) {
31 return cached;
32 }
33 if (template[0] === '#') {
34 const el = document.querySelector(template);
35 if ((process.env.NODE_ENV !== 'production') && !el) {
36 warn(`Template element not found or is empty: ${template}`);
37 }
38 // __UNSAFE__
39 // Reason: potential execution of JS expressions in in-DOM template.
40 // The user must make sure the in-DOM template is trusted. If it's rendered
41 // by the server, the template should not contain any user data.
42 template = el ? el.innerHTML : ``;
43 }
44 const { code } = compile(template, extend({
45 hoistStatic: true,
46 onError: (process.env.NODE_ENV !== 'production') ? onError : undefined,
47 onWarn: (process.env.NODE_ENV !== 'production') ? e => onError(e, true) : NOOP
48 }, options));
49 function onError(err, asWarning = false) {
50 const message = asWarning
51 ? err.message
52 : `Template compilation error: ${err.message}`;
53 const codeFrame = err.loc &&
54 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
55 warn(codeFrame ? `${message}\n${codeFrame}` : message);
56 }
57 // The wildcard import results in a huge object with every export
58 // with keys that cannot be mangled, and can be quite heavy size-wise.
59 // In the global build we know `Vue` is available globally so we can avoid
60 // the wildcard object.
61 const render = (new Function('Vue', code)(runtimeDom));
62 render._rc = true;
63 return (compileCache[key] = render);
64}
65registerRuntimeCompiler(compileToFunction);
66
67export { compileToFunction as compile };