vite-plugin-main-transform

⚡️ A Vite plugin which allows you transform main.js with Node.js API

Usage no npm install needed!

<script type="module">
  import vitePluginMainTransform from 'https://cdn.skypack.dev/vite-plugin-main-transform';
</script>

README

vite-plugin-main-transform

⚡️ Custom transform your main.js(.ts) in your vue project, auto import and global register Vue component(optional)

English | 简体中文

Install

  • First of all, install vite v2.x

  • Then install the plugin

$ npm i -D vite-plugin-main-transform
# OR
$ yarn add -D vite-plugin-main-transform

Usage

Write vite config

// vite.config.js
import mainTransform from 'vite-plugin-main-transform'

export default {
  plugins: [
    mainTransform({
      transformer: (code, { fs, path, babel, dirname }) => {
        // read main.js and concat its content into main.js
        const mainFile = fs.readFileSync(path.resolve(dirname, 'src/main.js'))
        return `${code}\nconst main = \`${mainFile}\``
      }
    })
  ]
}

Preview

code preview

Another usage

Write vite config

// vite.config.js
import mainTransform from 'vite-plugin-main-transform'

export default {
  plugins: [
    mainTransform({
      main: './src/main.ts',
      // auto scan files,  import and regsiter components.
      includes: ['./src/components/**/*.vue', './src/components/**/*.tsx']
    })
  ]
}

If src/components contains file foo.vue and bar.tsx, run with the config above, the result is:

// main.ts before
import Vue from 'vue';
// main.ts after
import Vue from 'vue';
import foo from './foo.vue';
import bar from './bar.tsx';

Vue.component('foo', foo);
Vue.component('bar', bar);

Options

main

Type: String
Default: ./src/main.js

Script path to be transformed

transformer

Type: Function((code, { fs, path, babel, dirname }) => string)
Default: null

code transformer function, the return value is the code transformed

include

Type: Array[...String]
Default: ['./src/components/**/*.vue']

An array of minimatch patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.

semicolon

Type: Boolean
Default: true

Add semicolon at the end of lines or not.

extension

Type: Boolean
Default: true

Keep file extension for import file or not.