Use vue-cli3+rollup+plop to build npm plug-ins

Installing vue frame

Run the following command to create a new project:

vue create zys-npm-rollup-plop-program

cd zys-npm-rollup-plop-program

yarn run serve

Install rollup.js and dependencies

rollup.js is a JavaScript module packer that can compile small pieces of code into large pieces of complex code, such as libraries or applications. Here we begin to install the related dependencies.

yarn add rollup rollup-plugin-vue rollup-plugin-css-only @rollup/plugin-node-resolve @rollup/plugin-alias @rollup/plugin-commonjs @rollup/plugin-babel @rollup/plugin-json -D

Configure rollup

The configuration file is an ES6 module that exposes an object that contains some options required by Rollup. Usually, we call this configuration file rollup.config.js, which is usually located in the root directory of the project. I put it under the build folder to facilitate subsequent module management.

// rollup.config.js

export default inputs.map((name) => ({
  input: path.resolve(__dirname, `../packages/${name.split('@pc-component/')[1]}/index.js`),
  output: [
    {
      format: 'es',
      file: getOutFile(name, 'es'),
      paths(id) {
        if (/^@pc-component/.test(id)) {
          if (noElPrefixFile.test(id)) return id.replace('@pc-component', '..');
          return id.replace('@pc-component/', '../op-');
        }
      },
    },
    {
      format: 'cjs',
      file: getOutFile(name, 'lib'),
      exports: 'named',
      paths(id) {
        if (/^@pc-component/.test(id)) {
          if (noElPrefixFile.test(id)) return id.replace('@pc-component', '..');
          return id.replace('@pc-component/', '../op-');
        }
      },
    },
  ],
 }));

Configure the output parameter through rollup to define the packaged file name and data format. Through packaging, two folders are output, es and cjs, corresponding to es6 Module and CommonJS Module respectively.

Add a script in package.json

"build:components": "rollup --config ./build/rollup.config.js",

Package the specified module code by executing the script command of rollup.config.js.

Install plop

yarn add plop -D

plop can generate and process file template code through the command line. By configuring the template, the directory structure of each module can be the same, reducing the trouble of pasting and copying. The automation is realized by one click template generation, which greatly improves the development efficiency.

Configure plop

Create plopfile.js in the root directory. Plopfile starts its life as a low-level node module. It exports a function that accepts the plop object as its first parameter. The plop object exposes the plop api object containing the setGenerator(name, config) function. The functions of the generator can be created through plopfile. When plop runs from a terminal in this directory (or any subdirectory), a list of these generators is displayed.

// plopfile.js
module.exports = (plop) => {
  plop.setGenerator('start', {
    description: 'A new project will be created',
    prompts: [
      {
        type: 'input',
        name: 'name',
        message: 'entry name',
        default: 'demo',
      },
    ],
    actions: [
      {
        type: 'add',
        path: 'packages/{{name}}/__test__/index.js',
      },
      {
        type: 'add',
        path: 'packages/{{name}}/src/index.vue',
        templateFile: 'plop-templates/vue-template.vue.hbs',
      },
      {
        type: 'add',
        path: 'packages/{{name}}/index.js',
        templateFile: 'plop-templates/index-template.hbs',
      },
      {
        type: 'add',
        path: 'packages/{{name}}/package.json',
        templateFile: 'plop-templates/package-template.json.hbs',
      },
    ],
  });
};

Configure hhs template

Create the plop Templates folder in the root directory, where you can write the corresponding template files. The template file is used to write the template content of the generated file, which can be defined according to the project requirements. The following is a vue template:

// vue-template.vue.hbs
<template>
  <div>{{name}}</div>
</template>

<script>
export default {
  name: 'op-{{name}}'
}
</script>

<style scoped>
</style>

Add a script in package.json

"plop": "plop start"

Generate the template file by running npm run plop.

Configure packaging entry

Create an index folder in the packages directory for the entry of the plug-in.

// index.js
import * as components from './components';

export * from './components';
const install = (app) => {

  Object.keys(components).forEach((c) => {
    app.use(components[c]);
  });

};

export default { install };

Add a script in package.json

"build-bundle": "vue-cli-service build --target lib --name zys-compnonent ./packages/index/index.js"

Through -- target in Vue cli's packaging script, you can specify whether the current project is of app or lib type

Package project

  • Package vue into lib

npm run build-bundle

  • Package a component through rollup

npm run build:components

After obtaining the package file, you can import the components in the es directory into the current project to test whether the components can be imported normally.

<template>
  <div id="app">
    <OpModule />
  </div>
</template>

<script>
import OpModule from '../es/op-module/index'

export default {
  name: 'App',
  components: {
    OpModule
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Components can be displayed normally.

Push to npm warehouse

npm publish

npm warehouse pushed successfully.

Pull plug-in from npm

yarn add zys-npm-rollup-plop-program -S

  • Register components
// main.js
import Vue from 'vue'
import App from './App.vue'
import zysCompnonent from 'zys-npm-rollup-plop-program'
Vue.config.productionTip = false

// Pull the plug-in and register
Vue.use(zysCompnonent)

new Vue({
  render: h => h(App),
}).$mount('#app')

  • Use components
// App.vue
<template>
  <div id="app">
    <op-module />
  </div>
</template>

<script>
// import OpModule from '../es/op-module/index'

export default {
  name: 'App',
  // components: {
  //   OpModule
  // }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  • The page is now pulling plug-in components from npm

Visible Thinking

  • Subsequently, lerna can be introduced for subcontracting management to reduce the dependency between packages

  • At present, components are imported globally, and can be imported on demand later

PS: the source code has contributed to you. Welcome to visit gitHub

Tags: Javascript npm Vue Vue.js

Posted on Mon, 11 Oct 2021 00:26:41 -0400 by kishore_marti