代码之家  ›  专栏  ›  技术社区  ›  samanime

转换单个文件。vue组件到JavaScript?

  •  21
  • samanime  · 技术社区  · 8 年前

    有没有一种工具可以 .vue 模板如下:

    <template>
      <div>Hello, {{ thing }}</div>
    </template>
    
    <script>
      export default {
        data() { return { thing: 'World' }; }
      }
    </script>
    
    <style>
      div { background: red; }
    </style>
    

    并将其转换为 .js 文件,如下所示:

    export default {
      template: `
        <div>Hello {{ thing }}</div>
      `,
      data() {
        return {
          thing: 'World'
        }
      }
    }
    

    (不知道它对CSS有什么魔力,但它会起到一些作用。)

    我正在尝试使用本机浏览器模块,它工作得很好,但我想使用 .vue 文件语法,因为它提供了一些好东西。我想避免使用像Webpack或Browserify这样的捆绑程序。

    我用的是巴别塔。我有 transform-vue-jsx 插件,但无法处理 .vue 格式,仅转换JSX。

    4 回复  |  直到 8 年前
        1
  •  16
  •   Decade Moon    8 年前

    您可以利用 vue-template-compiler 要分析*。vue文件并提取相关部分。

    我已经编写了一个节点脚本来完成这项工作:

    转换js公司

    const compiler = require('vue-template-compiler');
    
    let content = '';
    
    process.stdin.resume();
    
    process.stdin.on('data', buf => {
        content += buf.toString();
    });
    
    process.stdin.on('end', () => {
        const parsed = compiler.parseComponent(content);
        const template = parsed.template ? parsed.template.content : '';
        const script = parsed.script ? parsed.script.content : '';
    
        const templateEscaped = template.trim().replace(/`/g, '\\`');
        const scriptWithTemplate = script.match(/export default ?\{/)
            ? script.replace(/export default ?\{/, `$&\n\ttemplate: \`\n${templateEscaped}\`,`)
            : `${script}\n export default {\n\ttemplate: \`\n${templateEscaped}\`};`;
    
        process.stdout.write(scriptWithTemplate);
    });
    

    转换全部*。vue文件到*。vue。js,在包含*的目录中运行以下bash命令。vue文件(假设您使用的是linux或macOS):

    find . -name '*.vue' -exec bash -c 'node convert.js < "{}" > "{}.js"' \;
    

    这将导致以下转换:

    富。vue

    <template>
        <div>a</div>
    </template>
    
    <script>
        export default {
            name: 'foo',
        };
    </script>
    
    <style>
        /* Won't be extracted */
    </style>
    

    富。vue。js(已生成)

    export default {
        template: `
            <div>a</div>
        `,
        name: 'foo',
    };
    

    您可能希望调整脚本,使其能够处理提取样式(无论您希望如何处理)和修复空白之类的内容。

        2
  •  2
  •   Joshua Angnoe    5 年前

    我已经组装了一个在线vue转换器,它允许您复制/粘贴vue文件并将其转换为上述javascript。

    https://fluxfx.nl/htools/vue-conv

    Online Vue Converter

        3
  •  1
  •   Luckylooke    6 年前

    这是我对Typescript的编辑

    const parser = require("vue-template-compiler");
    const fs = require("fs");
    const path = require("path");
    const glob = require("glob");
    
    function getFiles(src, callback) {
      glob(src + "/**/*.vue", callback);
    }
    
    getFiles(path.join(__dirname, "../src"), function(err, filePaths) {
      if (err) {
        console.log("Error", err);
      } else {
        filePaths.forEach(filePath => {
          fs.readFile(filePath, "utf8", (err, data) => {
            if (err) throw err;
            const parsed = parser.parseComponent(data);
            if (!parsed.script) {
              return;
            }
            fs.writeFile(
              filePath.replace("vue", "ts"),
              parsed.script.content,
              err => {
                if (err) throw err;
                console.log(`The file ${filePath} has been created!`);
              }
            );
          });
        });
      }
    });
    

    我使用它对typscript代码进行sonarcube静态分析,因为sonarcube目前不支持vue SFC。

    并没有清理,因为我正在gitlab管道中运行它,所以在管道完成后,它会自动清理。

    谢谢:)

        4
  •  1
  •   Ben Hoffmann    4 年前

    以下是适用于Vue 3单文件组件的更新版本:

    包裹json:

    {
          "name": "vue3-sfc-convert",
          "version": "3.0.0",
          "description": "",
          "main": "convert.js",
          "scripts": {
            "convert": "node convert.js"
          },
          "author": "",
          "license": "ISC",
          "dependencies": {
            "glob": "^7.2.0",
            "vue": "^3.2.20"
          },
          "devDependencies": {
            "@vue/compiler-sfc": "^3.2.20"
          }
    }
    

    转换js公司

    /**
     * convert.js
     * 
     * Convert Vue3 Single File Component to stand-alone script with template property
     * Run node convert.js in directory containing *.vue files
     * Output will be .vue files converted to .ts files with template property set to contents of SFC template block
     */
    const sfcCompiler = require("@vue/compiler-sfc");
    const fs = require("fs");
    const glob = require("glob");
    
    const COMPONENT_START = "export default defineComponent({";
    
    function convertSFC(filePath) {
      try {
        fs.readFile(filePath, "utf8", (err, data) => {
          if (err) {
            console.log(err);
          } else {
            try {
              const parsed = sfcCompiler.parse(data);
              if (!parsed.descriptor) {
                return;
              }
              let templateEncoded = parsed.descriptor.template
                  ? parsed.descriptor.template.content
                      .replace(/[\n\r]/gi, " ")
                      .replace(/\"/gi, '\\"')
                      .replace(/\s\s+/gi, " ")
                  : null,
                templateLine = templateEncoded ? `\ntemplate: "${templateEncoded}",\n` : "",
                justScript = parsed.descriptor.script.content,
                startPos = justScript.indexOf(COMPONENT_START),
                scriptAndTemplate =
                  justScript.substring(0, startPos + COMPONENT_START.length) +
                  templateLine +
                  justScript.substring(startPos + COMPONENT_START.length);
              fs.writeFile(
                filePath.replace("vue", "ts"),
                scriptAndTemplate,
                (err) => {
                  if (err) throw err;
                  console.log(`The file ${filePath} has been created!`);
                }
              );
            } catch (parseError) {
              console.log(parseError);
            }
          }
        });
      } catch (readError) {
        console.log(readError);
      }
    }
    
    glob("**/*.vue", {}, (err, files) => {
      console.log(`Convert ${files.length} SFCs...`);
      files.forEach((filePath) => {
        convertSFC(filePath);
      });
    });