提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB

  1. import { parse, compileScript } from '@vue/compiler-sfc';
  2. import MagicString from 'magic-string';
  3. function supportScriptName(code, id) {
  4. let s;
  5. const str = () => s || (s = new MagicString(code));
  6. const { descriptor } = parse(code);
  7. if (!descriptor.script && descriptor.scriptSetup) {
  8. const result = compileScript(descriptor, { id });
  9. const name = result.attrs.name;
  10. const lang = result.attrs.lang;
  11. if (name) {
  12. str().appendLeft(0, `<script ${lang ? `lang="${lang}"` : ""}>
  13. import { defineComponent } from 'vue'
  14. export default defineComponent({
  15. name: '${name}',
  16. })
  17. <\/script>
  18. `);
  19. }
  20. return {
  21. map: str().generateMap(),
  22. code: str().toString()
  23. };
  24. } else {
  25. return null;
  26. }
  27. }
  28. const index = (options = {}) => {
  29. return {
  30. name: "vite:setup-name-support",
  31. enforce: "pre",
  32. async transform(code, id) {
  33. if (!/\.vue$/.test(id)) {
  34. return null;
  35. }
  36. const { name = true } = options;
  37. if (name) {
  38. return supportScriptName.call(this, code, id);
  39. }
  40. return null;
  41. }
  42. };
  43. };
  44. export { index as default };