1
0
mirror of https://github.com/sahadev/vue-component-creater-ui.git synced 2025-09-28 07:13:21 +08:00

update: 精简依赖库

This commit is contained in:
shangbin
2021-12-03 18:24:48 +08:00
parent 936d98f03d
commit 1f9171814d
7 changed files with 86 additions and 589 deletions

View File

@@ -1,125 +0,0 @@
<template>
<preview :value="preview" class="panel"></preview>
</template>
<script>
import Preview from '@/components/Preview';
import { parseComponent } from 'vue-template-compiler/browser';
import getImports from '@/utils/get-imports';
import getPkgs from '@/utils/get-pkgs';
import isAbsouteUrl from 'is-absolute-url';
import * as params from '@/utils/params';
export default {
props: ['code'],
components: {
Preview
},
data: () => ({
preview: '',
}),
watch: {
code: {
handler: function (newValue) {
this.compile(newValue);
},
immediate: true
}
},
methods: {
async compile(code) {
if (!code) {
return;
}
const imports = [];
const { template, script, styles, customBlocks } = parseComponent(code);
let config;
if ((config = customBlocks.find(n => n.type === 'config'))) {
params.clear();
params.parse(config.content);
}
let compiled;
const pkgs = [];
let scriptContent = 'exports = { default: {} }';
if (script) {
try {
compiled = window.Babel.transform(script.content, {
presets: ['es2015', 'es2016', 'es2017', 'stage-0'],
plugins: [[getImports, { imports }]]
}).code;
} catch (e) {
this.preview = `<pre style="color: red">${e.message}</pre>`;
return;
}
scriptContent = await getPkgs(compiled, imports, pkgs);
}
const heads = this.genHeads();
const scripts = [];
pkgs.forEach(pkg => {
scripts.push(
`<script src=//packd.now.sh/${pkg.module}${pkg.path}?name=${pkg.name
}><\/script>`
);
});
styles.forEach(style => {
heads.push(`<style>${style.content}</style>`);
});
scripts.push(`
<script>
var exports = {};
${scriptContent}
var component = exports.default;
component.template = component.template || ${JSON.stringify(
template.content
)}
new Vue(component).$mount('#app')
<\/script>`);
this.preview = {
head: heads.join('\n'),
body: '<div lc_id="app"></div>' + scripts.join('\n')
};
},
genHeads() {
let heads = [];
const { pkgs, css } = params.get();
return [].concat(
[]
.concat(pkgs)
.map(
pkg =>
`<script src="${isAbsouteUrl(pkg) ? '' : prefix}${pkg}"><\/script>`
),
css.map(
item =>
`<link rel=stylesheet href="${isAbsouteUrl(item) ? '' : prefix
}${item}">`
)
);
},
}
};
</script>
<style src="modern-normalize"></style>
<style scoped>
.panel {
background-color: white;
}
</style>

View File

@@ -1,18 +0,0 @@
export default function(code, { imports }) {
return {
name: 'get-imports',
visitor: {
ImportDeclaration(path) {
imports.push({
variables: path.node.specifiers.map(spec => ({
local: spec.local.name,
imported: spec.imported ? spec.imported.name : 'default'
})),
module: path.node.source.value
});
path.remove();
}
}
};
}

View File

@@ -1,40 +0,0 @@
import parsePackageName from 'parse-package-name';
export default async function(code, imports, scripts) {
const replacements = [];
for (const [index, item] of imports.entries()) {
const moduleName = `__npm_module_${index}`;
const pkg = parsePackageName(item.module);
const version = pkg.version || 'latest';
scripts.push({
path: pkg.path ? `/${pkg.path}` : '',
name: moduleName,
module:
pkg.name === 'vue' && !pkg.path
? `vue@${version}/dist/vue.esm.js`
: `${pkg.name}@${version}`
});
let replacement = '\n';
for (const variable of item.variables) {
if (variable.imported === 'default') {
replacement += `var ${
variable.local
} = ${moduleName}.default || ${moduleName};\n`;
} else {
replacement += `var ${variable.local} = ${moduleName}.${
variable.imported
};\n`;
}
}
if (replacement) {
replacements.push(replacement);
}
}
if (replacements.length > 0) {
code = replacements.join('\n') + code;
}
return code;
}

View File

@@ -1,59 +0,0 @@
/**
* From: https://github.com/egoist/codepan/blob/2c22bb3d7a7a4e31fd99fc640d320f7ec24d2951/src/utils/iframe.js
*/
import { Loading } from 'element-ui';
class Iframe {
constructor({ container, el, sandboxAttributes = [] }) {
if (!el) {
throw new Error('Expect "el" to mount iframe to!');
}
this.$container = container;
this.$el = el;
this.sandboxAttributes = sandboxAttributes;
}
setHTML(obj) {
let html;
if (typeof obj === 'string') {
html = obj;
} else {
const { head = '', body = '' } = obj;
html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
}
// 关闭上一个实例引起的loading
if (this.loadingInstance) {
this.loadingInstance.close();
}
this.loadingInstance = Loading.service({
target: this.$container,
text: '渲染中,请稍后...'
});
const iframe = this.createIframe();
iframe.addEventListener('load', () => {
this.loadingInstance.close();
})
this.$el.parentNode.replaceChild(iframe, this.$el);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
this.$el = iframe;
}
createIframe() {
const iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', this.sandboxAttributes.join(' '));
iframe.setAttribute('scrolling', 'yes');
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = '0';
return iframe;
}
}
export default (...args) => new Iframe(...args);

View File

@@ -1,55 +0,0 @@
import qs from 'query-string';
import deepmerge from 'deepmerge';
const DEFAULT_PARAMS = {
pkgs: ['https://static.imonkey.xueersi.com/vue-code-creater/resource/vue.js', 'https://static.imonkey.xueersi.com/vue-code-creater/resource/element-ui/index.js'],
css: ['https://static.imonkey.xueersi.com/vue-code-creater/resource/element-ui/index.css'],
};
let params = DEFAULT_PARAMS;
function getArr(str) {
if (Array.isArray(str)) {
return str;
}
if (typeof str === 'string') {
return str.split(',');
}
return [];
}
export function clear() {
params = DEFAULT_PARAMS;
}
export function parse(str) {
try {
merge(JSON.parse(str));
} catch (e) {
console.error('error', e.message);
}
}
export function queryParse(str) {
const query = qs.parse(str);
const pkgs = getArr(query.pkg);
const css = getArr(query.css);
const options = { pkgs, css };
if (query.cdn) {
options.cdn = query.cdn;
}
if (query.vue) {
options.vue = query.vue;
}
merge(options);
}
export function get() {
return deepmerge(DEFAULT_PARAMS, params);
}
export function merge(opts) {
params = deepmerge(params, opts);
}