This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
0 x00 preface
This article will explain the construction process of vue-code-View project from the aspects of structure and function. You can know the following:
- use
vue cli 4
Build a component library and detailed configuration information from 0. - Multi-environment build configuration for the project.
- Release deployment and continuous integration of the project website.
- Project NPM package released.
- Customization of project components
Markdown
parsingloader
.
This article is an extension of πElement 2 source code learning series. After understanding the structure principle of the open source component library through the previous article, how to build a component project? The following is the process of practice, is the “unity of knowledge and action” bar! Read patiently, I believe it will help you!
0x01 Project Overview
Create a project
This project uses Vue CLI 4.x to create a project.
// Installation environment NPM install -g@vue /cli // Create project vue create vue-code-viewCopy the code
After entering the command in the terminal, follow these steps to create the project:
- Select the manual selection function
Manually select features
. - The selected
Babel
.Router
.CSS Pre-processors
.Linter / Formatter
, and other functions. - choose
vue
version2.X
- Select whether to use a route
history
Mode, defaultyes
. - Select the CSS preprocessor
Sass/SCSS(with node-sass)
. - Select code style and format verification
linter / formatter
configurationESLint + Prettier
. - Select checksum time save detection
Lint on save
- choose
Babel
.ESLint
Such configuration files are stored in dedicated configuration filesIn dedicated config files
.
Configure multiple environment variables
In the project root directory. The new env,. The env. Deploy,. The env. The production and other documents.
Variables starting with VUE_APP are statically embedded in the client-side package by webpack.defineplugin and can be accessed in the code through process.env.vue_app [XXX].
NODE_ENV and BASE_URL are two special variables that are always available in the code.
Env vue-cli-service serve Default local development environment configuration
NODE_ENV = development
VUE_APP_PUBLIC_PATH = /
Copy the code
.env.production vue-cli-service build Default environment configuration (formal server)
NODE_ENV = production
VUE_APP_PUBLIC_PATH = /
VUE_APP_ENV = pub
Copy the code
.env.deploy to github pages to build the deployed environment configuration. VUE_APP_PUBLIC_PATH /vue-code-view Is used for virtual directories.
NODE_ENV = production
VUE_APP_PUBLIC_PATH = /vue-code-view
VUE_APP_ENV = deploy
Copy the code
Directory structure adjustment
The default SRC directory holds the project source code and the resource files that need to be referenced. Create a new examples folder under the root directory for the project example site and move the files from the SRC directory to examples. The SRC directory holds the source code for the project components.
The structure of the root directory file is as follows:
β β β examples / / project example website | β β β App. Vue | β β β assets | β β β components | β β β the main, js | β β β the router | β β β views β β β SRC / / Project component source | β β β fonts | β β β index. The js | β β β the locale | β β β mixins | β β β the SRC | β β β styles | β β β utils β β β public β β β package.jsonCopy the code
Configure basic vue.config.js
/ SRC /main.js, configured as follows:
{
entry: {
app: [
'./src/main.js']}}Copy the code
Create vue.config.js in the root directory to modify the default configuration.
const path = require("path");
const resolve = (dir) = > path.join(__dirname, dir);
module.exports = {
configureWebpack: (config) = > {
// Project entry
config.entry.app = "./examples/main.js";
},
chainWebpack: (config) = > {
// Add an alias
config.resolve.alias
.set("vue$"."vue/dist/vue.esm.js")
.set("@", resolve("examples"))
.set("@assets", resolve("examples/assets"))
.set("@src", resolve("src"))
.set("@views", resolve("examples/views"))
.set("@router", resolve("examples/router"))
.set("@store", resolve("examples/store")); }};Copy the code
Run NPM Run serve and the project website runs normally.
0x02 Project build
NPM scripts to configure
Adjust the scripts configuration script in package.json and add –mode XXX to select different environment configurations.
"scripts": {
// Development environment launch project sample site
"dev": "vue-cli-service serve ".// Component library build
"dist": "vue-cli-service build --mode production --target lib --name vue-code-viewer --dest lib src/index.js".// Project example website construction
"deploy:build": "vue-cli-service build --mode deploy"
}
Copy the code
Components to build
Component libraries are built by specifying the entry file SRC /index.js and setting the parameter options.
Usage: vue cli - service build [options] [entry | pattern] parameter options: - mode specified environment mode (default: production), dest specifies the output directory (default: dist) --target app | lib | wc | wc-async(Default: app) -- Name specifies the name of the library or Web Components mode (default: package.json)"name"Field or entry file name)Copy the code
Building a library outputs:
lib/vue-code-viewer.common.js
: a CommonJS package for packagers.lib/vue-code-viewer.umd.js
: a UMD package directly for use by browsers or AMD loaders.lib/vue-code-viewer.umd.min.js
: Compressed UMD build version.lib/vue-code-viewer.css
: Extracted CSS file.
Component NPM package released
Configure the property values in the package.json file for NPM publishing.
- Name: package name, which is unique. You need to go to NPM Registry to see if the name is already in use.
- Version: indicates the package version number. For the version number rule, see Semantic Version 2.0.0. The version number must be changed each time you release to NPM. The version number cannot be the same as the historical version number.
- Description: Describes the main functions and uses of the package.
- Main: entry file. This field should point to the compiled package file of the project.
- Unpkg: UMD mode entry package file
- Keyword: array or string.
- Author: indicates the author of the package.
- Private: indicates whether to publish to NPM. Change the value to false
- License: Open source agreement.
- Repository: Git Repo information for a package, including type and URL.
- Homepage: The url of the project’s official website.
Update package.json file contents:
{
"name": "vue-code-view"."version": "0.3.9"."description": "A code editor component based on Vue.js 2 "."main": "lib/vue-code-viewer.common.js"."unpkg": "lib/vue-code-viewer.umd.js"."scripts": {},
"dependencies": {},
"peerDependencies": {},
"devDependencies": {},
"keywords": [
"vue"."components"."codemirror"."code editor"]."repository": {
"type": "git"."url": "git+https://github.com/andurils/vue-code-view.git"
},
"author": "andurils"."license": "MIT"."homepage": "https://andurils.github.io/vue-code-view"
}
Copy the code
Add.npmignore file, set to ignore publish file. Publish files to NPM, keep only the lib directory, package.json, readme.md.
# ignore directory
examples/
node_modules/
public/
build/
src/
dist/
deploy/
# ignore the specified file
.browserslistrc
.eslintignore
.prettierignore
.env
.env.*
*.js
Copy the code
Then log in to nPMjs.com and run the NPM publish command to publish the component package.
After the release, go to NPM /vue-code-view on the NPM home page of the component and view the project configuration information.
Project example website construction
Update vue.config.js and run NPM run deploy:build to export the sample build project site to the deploy directory.
const path = require("path");
const resolve = (dir) = > path.join(__dirname, dir);
const IS_PROD = ["production"."prod"].includes(process.env.NODE_ENV);
module.exports = {
publicPath: process.env.VUE_APP_PUBLIC_PATH || "/".productionSourceMap: false.outputDir: process.env.VUE_APP_ENV === "deploy" ? "deploy" : "dist".configureWebpack: (config) = > {
// Project entry
config.entry.app = "./examples/main.js"},... };Copy the code
Continuous integration
The project sample site is automatically built and deployed to the GH-Pages branch using Travis CI’s Continuous integration service.
Add the.travis. Yml file to the root directory to specify the behavior of Travis. By setting up a new Commit in the repository, Travis will go to the file and execute the commands (build, deploy, etc.). y
sudo: false
language: node_js
node_js: 14
install:
- yarn
script: npm run deploy:build
after_script:
- mkdir temp_web
- cd temp_web
- git clone --depth 1 -b gh-pages --single-branch https://${TravisCI_Token}@${GH_REF} && cd vue-code-view
- echo 'copy && commit'- rm -rf js fonts - cp -rf .. /.. /deploy/** . - git config user.name"${U_NAME}"
- git config user.email "${U_EMAIL}"
- git add -A .
- git commit -m ":construction_worker:- Build & Deploy by Travis CI"
- git push origin gh-pages
- echo "DONE, Bye~"
- exit 0
Copy the code
Travis CI project construction background:
Turn on build compression
Install related plug-ins.
# gzip webpack 4.x corresponds to version 6.xNPM [email protected] - I D# Code compression
npm iΒ uglifyjs-webpack-plugin -D
Copy the code
Configure vue.config.js and enable the plug-in.
.const IS_PROD = ["production"."prod"].includes(process.env.NODE_ENV);
// gzip compressed webpack 4.x corresponds to 6.x version CNPM I [email protected] --save-dev
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\? . *)? $/i;
// Code compression
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
module.exports = {
...
configureWebpack: (config) = > {
const plugins = [];
// Configuration related to production environment
if (IS_PROD && process.env.VUE_APP_ENV === "pub") {
plugins.push(
new CompressionWebpackPlugin({
filename: "[path][base].gz".algorithm: "gzip".minRatio: 0.99.test: productionGzipExtensions,
deleteOriginalAssets: false,})); plugins.push(new UglifyJsPlugin({
uglifyOptions: {
// Delete comments
output: {
comments: false,},// Delete the console debugger
compress: {
drop_debugger: true.drop_console: true.// console
pure_funcs: ["console.log"]./ / remove the console
},
// Delete the warning
warnings: false,},sourceMap: false.parallel: true.// Use multiple processes running in parallel to speed up builds. Default number of concurrent runs: os.cpus().length-1.})); } config.plugins = [...config.plugins, ...plugins]; }};Copy the code
Component Description Document
See element 2’s implementation for a custom build/md-loder to parse and render Markdown files and compile examples\docs\ zh-cn \example.md into HTML. This chapter has been described in the previous chapter 04. Packaging Component Packaging and Preparation.
Configure vue.config.js and add a custom Markdown Loader for the.md file.
module.exports = {
...
configureWebpack: (config) = > {
config.resolveLoader.modules = ["node_modules"."./build/"]; // Customize loader
},
chainWebpack: (config) = > {
// Markdown Loader
config.module
.rule("md")
.test(/\.md/)
.use("vue-loader")
.loader("vue-loader")
.end()
// Customize loader
.use("md-loader")
.loader("md-loader") .end(); }};Copy the code
Examples router index.js Configure routes:
const routes = [
{
path: "/md".name: "Markdown".component: (r) = >
require.ensure([], () = > r(require(".. /docs/zh-CN/example.md"))),},];Copy the code
0 x03 end
This section mainly in accordance with the project from simple to complex shun search gradually explained the operation items and details configuration. The component implementation principles are explained in detail below.
To be continued