Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert single-file .vue components to JavaScript?

Is there a tool out there that can take a .vue template like this:

<template>
  <div>Hello, {{ thing }}</div>
</template>

<script>
  export default {
    data() { return { thing: 'World' }; }
  }
</script>

<style>
  div { background: red; }
</style>

And convert it into a .js file, like this:

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

(Not sure what magic it'd do with the CSS, but it'd do something.)

I'm trying to use native browser modules, which work great, but I'd like to use the .vue file syntax since it offers some nice things. I'd like to avoid using a bundler like Webpack or Browserify.

I am using Babel. I have the transform-vue-jsx plugin, but that can't handle the .vue format, only converting the JSX.

like image 985
samanime Avatar asked Dec 13 '17 04:12

samanime


People also ask

How do I import a Vue component into JavaScript?

There are two ways to import a JavaScript library to the Vue Component. The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey.

What is single file components?

Single File Components(SFCs) are a style of application organization used by JavaScript UI libraries where each file represents a single component in all aspects. Typically they resemble an HTML document where you have HTML tags, Style Tag, and Script Tag all in a file.


3 Answers

You can utilize vue-template-compiler to parse the *.vue files and extract the relevant sections.

I've written a node script which should do the job:

convert.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);
});

To convert all *.vue files to *.vue.js, run the following bash command inside the directory containing the *.vue files (assuming you're using linux or macOS):

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

This will result in the following conversion:

foo.vue

<template>
    <div>a</div>
</template>

<script>
    export default {
        name: 'foo',
    };
</script>

<style>
    /* Won't be extracted */
</style>

foo.vue.js (generated)

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

You might want to tweak the script so that it deals with extracting the styles (however you want that to be handled) and fixing up whitespace and stuff like that.

like image 72
Decade Moon Avatar answered Nov 03 '22 03:11

Decade Moon


I've put together an online vue converter which allows you to copy/paste your vue-file and convert it to said javascript.

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

Online Vue Converter

like image 21
Joshua Angnoe Avatar answered Nov 03 '22 03:11

Joshua Angnoe


This is my edit for 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!`);
          }
        );
      });
    });
  }
});

I am using it for sonarcube static analyses of my typscript codes, since sonarcube does not support vue SFC for now.

There is no cleanup, because I am running it in gitlab pipeline so after pipeline is done, it is all cleaned automatically.

Thanks :)

like image 29
Luckylooke Avatar answered Nov 03 '22 02:11

Luckylooke