Preface
This article will reveal the secret of vue-sfc-cli, a powerful tool for developing vue single-file component, and explain how it improves efficiency throughout the component development process.
This article can be seen as a growing part of 📦the best practices of publishing vue components to npm. It is a companion piece of 🤖setup and automated Github Workflow. It is the result of the team’s best practices. It involves a lot of background knowledge and may need to takes some time to understand🤔
Tutorial
Quick Start
npx vue-sfc-cli
​
# Next there will be a bunch of tips, please be sure to fill out
# Recommend kebab-case style, lowercase letters, multiple words separated by - (dash), such as my-component
​
# After filling the prompt
cd my-component
​
# Use git to initialize, so you can use the commit hook
git init
​
# Install dependency
yarn
​
# Develop component
yarn dev
​
# Build
yarn build
​
# ready to publish!
# or use npm publish
yarn publishOptions
-u, --upgrade
According to the template files in the templates directory, new files will be generated and override the files with same name in current component directory. The default override files is defined in update-files.js. This option often used to upgrade the configuration of old components using the latest version of vue-sfc-cli:
# cd my-component
npx vue-sfc-cli -u--files
If you want to update additional files, you can pass this option, followed by the file name, multiple files used , to separated
npx vue-sfc-cli -u --files package.json,.babelrc.js--test
Generate a test component template, commonly used in for testing.
npx vue-sfc-cli --testWriting Example
The docs directory hosts your component’s examples. You just write markdown files, and they will turn into demo. It is also recommended to name the markdown files in kebab-case style.
Take the docs/draggable.md file of upload-to-ali, the upload component as an example.
When you yarn dev, this markdown file will be turn into live demo, which will show you what the component looks like and it’s actual code. You can also modify the code and the demo can hot reload.
API documentation
You can simply write comments in vue file to generate API documentation.
props
Use multi-line comments in props
slot
On the previous line of the slot, comments beginning with @slot
event
Above the emit event, use multi-line comments
methods
Above the method to be publicly displayed, use a multi-line comment and add @public
Then the documentation looks like this:
Working with third-party libraries
Take Element-UI as an example
yarn add element-uiAdd a new file:styleguide/element.js
import Vue from 'vue'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Element)Modify the configuration file:styleguide.config.js
Environment Variables
If you need to use environment variables, it is recommended to use dotenv
yarn add dotenv --devprettier and husky
The component template has a built-in prettier and husky setup that can format code when you commit.。
However, you need to execute the git init command before running yarn ,otherwise the commit hook will not take effect.
Attention
It is not recommended to generate components under Windows, as .sh files may lost execution permissions.
Technical details
Overview
- Vue-styleguidist write demo and documentation
- Jest Unit test
- Prettier + husky code formatting
- Rollup packaging
- Standard-version automatically generate changelog
- Github-release-notes generate github release
- Auto-badge automatically add label for pull request
- Netlify for pull request preview
- Travis CI for npm publish and push to github pages
- The shell + dingtalk api sends a dingtalk message after releasing successfully
- All-contributors to show contributors
- Built-in README. md template, including directory structure, back to top, and some common badge
Template directory
The following is the generated component default template configuration
├── .all-contributorsrc # all-contributors configuration
├── .babelrc
├── .editorconfig
├── .github
│ └── badge.yml # github app auto-badge configuration for automatic labeling pr
├── .gitignore
├── .grenrc.js # github-release-notes configuration
├── .prettierignore # prettier configuration
├── .prettierrc # prettier configuration
├── .travis.yml # travis ci configuration
├── LICENSE # MIT
├── README.md # Readme
├──build #rollup configuration
│ └── rollup.config.js
├── build.sh # ci related files
├── dist # package output directory
├── docs # Using the documentation, these md fiels will be converted into demos
│ ├── basic.md
├── notify.sh # ci related files for nailing notifications
├── package.json
├── src # source file directory
│ ├── index.js
│ └── upload-to-ali.vue # single file component
├── styleguide.config.js # vue-styleguidist configuration file
└── yarn.lockDevelopment
The reason for choosing vue-styleguidist to developing is that the benefit of writing md can be both a document and a runnable demo.
That is to say, documentation and demo are the same file, you don’t need to maintain two copies of code at the same time.
Besides, with hot reload, whether modify markdown file or modify the source code vue file, the demo will refresh, it is very convenient.
Unit Testing
For component testing, the first thing that comes to mind may be vue-test-utils. Then you may feel that component testing is a bit hard to write, or that you don’t know how to write it.
In fact, you can think in another way and start with simple ones. To do unit test, it is more important to develop the habit of writing tests, so it is recommended to test only pure functions with jest at the beginning.
That is to say, you can extract the methods defined in the component, place them in a separate file, and then specifically test them.
The advantage is that to test these functions:
- When you write components methods, you need to write short and fine functions as much as possible.
- You will be encouraged write pure function, which does not depend on or affect the global variable.
This writing unit test method is also very suitable for gradually adding test cases to a component that is completely untested.
The following is a code example of el-data-table for pure function testing.
Here comes a related articles: ✅use jest for test-driven development
build
yarn build will generate three files:
- upload-to-ali.esm.js
- upload-to-ali.min.js
- upload-to-ali.umd.js
When the user imports the component, the default imported file is upload-to-ali.umd.js. Regarding the description of the three files, 📦the best practices of publishing vue component to npm have been explained so here will not repeat it.
One of the features of building by rollup is that the component’s dependencies are not packaged together by default. This feature helps to reduce the component’s distribution size.
Here’s an example:
// src/index.js
const crypto = require('crypto')
const axios = require('axios')running yarn build will get the following information:
Please don’t worry about this warning, this is intentional, because we don’t want to pack the dependencies into the dist.
Commit Specification
Let’s review Conventional Commits before continuing.
The key points are as follows, the format is:
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer><type>: <subject> is required
<type>may be one of them:
- feat: A new feature
- fix: A bug fix
- docs: Documentation only changes
- style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
- refactor: A code change that neither fixes a bug nor adds a feature
- perf: A code change that improves performance
- test: Adding missing or correcting existing tests
- chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
In addition, the update relies on the use of chore(deps), which is also the official practice of github.
PR automatic labeling
Since the release notes generated by github-release-notes will only work when the Pull Request marked with labels, add an auto-badge robot that automatically adds a label to the github PR to reduce mankind effort.
Process Details
.grenrc.js
.grenrc.js is the configuration of the github-release-notes. Here shows a configuration obtained after referring to nuxt, github and other popular repositories, which can be used immediately.
badge.yml
.github/badge.yml is the auto-badge configuration file that needs to be placed under the hidden folder .github. The following configuration corresponds to the above .grenrc.js, which can also be used immediately.
Automatic release
Travis CI
Mainly using Travis CI to set up an automated workflow, take a quick look at the following .travis.yml configuration:
For the specific description of the above parameters, you can refer to the tutorial: 🚀Github integrated with Travis CI: automatic release
Process Details
build.sh
The build.sh content is as follows:
#!/bin/sh
yarn stdver
​
yarn build
​
git remote add github https://$GITHUB_TOKEN@github.com/FEMessage/upload-to-ali.git > /dev/null 2>&1
git push github HEAD:master --follow-tagsCorrespondingly, the package.json’s scripts need to have the following fields:
"stdver": "standard-version -m '[skip ci] chore(release): v%s'",
"release": "gren release --override"The contents of notify.sh are as follows:
#!/bin/sh
if [ "$TRAVIS_TEST_RESULT" != "0" ]
then
echo "build not success, bye"
exit 1
fi
​
url=https://api.github.com/repos/FEMessage/upload-to-ali/releases/latest
resp_tmp_file=resp.tmp
​
curl -H "Authorization: token $GITHUB_TOKEN" $url > $resp_tmp_file
​
html_url=`cat $resp_tmp_file | sed -n 5p | sed 's/\"html_url\"://g' | awk -F '"' '{print $2}'`
body=`cat $resp_tmp_file | grep body | sed 's/\"body\"://g;s/\"//g'`
​
msg='{"msgtype": "markdown", "markdown": {"title": "upload-to-ali更新", "text": "@所有人\n# [upload-to-ali]('$html_url')\n'$body'"}}'
​
curl -X POST https://oapi.dingtalk.com/robot/send\?access_token\=$DINGTALK_ROBOT_TOKEN -H 'Content-Type: application/json' -d "$msg"
​
rm $resp_tmp_fileHere are two key points:
- Only send message when build successfully
- When you call the github api to get the latest release, add your github token
README.md
After referring to the excellent open source project, we searched out a set of README.md templates, built in the initialization project.
common and useful badges
contributors
you can find more detail about the meaning of emoji in official documents
Conclusion
Finally, welcome to use https://github.com/FEMessage/vue-sfc-cli to develop vue components ~
