mch-ui

Always wanted to make a set of UI, since came to the big city of Shanghai, all day busy with the company to write business, especially the epidemic, the company downsized, the work will be more busy, a person to do more personal work, and finally at the end of the year to recruit two front end, the pressure is finally small a lot, free to research and develop a set of UI library

The preparatory work

The vuE-Cli3.0 scaffolding tool needs to be installed. Because of the lazy relationship, I will not directly describe how to build a VUE project with webPack configuration step by step from NPM init. Instead, I will directly use vue-Cli3.0 to build a project. There is no technical difficulty, the only estimation required is that you understand that VUE-CLI3.0 is not VUe3.0.

If you also want to know how to build a DIY scaffolding tool, can you follow my tutorial, portal or just look at the source code

Begin to build

Step one, usevue create mch-uiThen press enter to the bottom and open the folder in vscode. You’ll find something like this in the table of contents.

This is a basic vue2.0 project directory. At this point, you can directly NPM I followed by NPM run serve and you can directly open a browser to access the project

Step 2: Modify the project directory. Obviously, this is not the project directory we want, so we need to

1. Change the SRC directory name to examples to show examples of components

2. Create a new Packages folder under the root directory for storing components

At this time, because we artificially modified the project folder name, the original project can not run normally, don’t worry, then look down.

Step 3: Add the configuration file

After all, the SRC is missing, so the path must be wrong. So now let’s solve this problem. Create a new vue.config.js file in the root directory (the new project doesn’t have this file) and write the following:

Const path = require('path') module.exports = {/* Builds multi-page mode applications. Each "page" should have a corresponding JavaScript item file. The value should be an object, where the key is the name of the item, and the value should be either an object specifying the item, template, and filename, or a string specifying the item. Note: {index: {entry: 'examples/main.js', // entry: 'public/index.html', // template filename: 'index.html' // output file}}, // modify pages entry chainWebpack: Config => {// @ default to SRC directory, Resolve ('examples'). Set ('@', path.resolve('examples')). Set ('~', package config.resoly.alias.set ('@', path.resolve('examples')). Path.resolve ('packages')) Because new files are not processed by webpack by default config.module.rule ('js').include.add(/packages/).end().include.add(/examples/).end() Use (' Babel). Loader (' Babel - loader). Tap (options = > {/ / modify it options... Return options})} // Extend webpack configuration}Copy the code

Vue-cli3.0 is much simpler than vue-Cli2.0. For example, the configuration information of the project is no longer exposed in the project. Instead, it is directly given to you after you create vue XX-xx. You write configuration information to package.json according to your options, and then after NPM I, the configuration information is stored in the @vue directory, so Vue3.0 fully encapsulates the configuration file. But, people are changeable, so out of human nature, You can also do DIY like Vue2.0 by adding vue.config.js to the root directory to tweak configuration options, including baseUrl, Pages, productionSourceMap, and more

Pages in vue. Config. js is because the directory of the folder has been changed and the import and export file needs to be reformulated. ChainWebpack modifies the webPack configuration in a chained manner and is often used to extend the WebPack configuration.

Here’s a quick overview of webPack’s configuration properties.

Config.module. rule(name).use(name).loader(loader).options(options) // an example config.module .rule('graphql') .test(/\.graphql$/) .use('graphql-tag/loader') .loader('graphql-tag/loader') .end() // Module :{rules:[{test:/\.graphql$/, Use ::[{loader:"graphql-tag/loader"}]}]} 2, set alias const path = require('path'); function resolve (dir) { return path.join(__dirname, dir) } module.exports = { lintOnSave: true, chainWebpack: (config)=>{ config.resolve.alias .set('@$', resolve('src')) .set('assets',resolve('src/assets')) .set('components',resolve('src/components')) .set('layout',resolve('src/layout')) .set('base',resolve('src/base')) .set('static',resolve('src/static')) .delete('base') // delete the specified alias //.clear() will delete all aliases}} Config.entry ('main').add('./ SRC /main.js')// Add new entries Config.entry ('routes').add('./ SRC /app-routes.js')// Add config.output. path("dist").filename("[name].[chunkhash].js") .chunkFilename("chunks/[name].[chunkhash].js") .libraryTarget("umd") .library(); } config.output. auxiliaryComment(auxiliaryComment).chunkfilename (chunkFilename) .chunkLoadTimeout(chunkLoadTimeout) .crossOriginLoading(crossOriginLoading) .devtoolFallbackModuleFilenameTemplate(devtoolFallbackModuleFilenameTemplate) .devtoolLineToLine(devtoolLineToLine) .devtoolModuleFilenameTemplate(devtoolModuleFilenameTemplate) .filename(filename) .hashFunction(hashFunction) .hashDigest(hashDigest) .hashDigestLength(hashDigestLength) .hashSalt(hashSalt) .hotUpdateChunkFilename(hotUpdateChunkFilename) .hotUpdateFunction(hotUpdateFunction) .hotUpdateMainFilename(hotUpdateMainFilename) .jsonpFunction(jsonpFunction) .library(library) .libraryExport(libraryExport) .libraryTarget(libraryTarget) .path(path) .pathinfo(pathinfo) .publicPath(publicPath) .sourceMapFilename(sourceMapFilename) .sourcePrefix(sourcePrefix) StrictModuleExceptionHandling (strictModuleExceptionHandling). UmdNamedDefine (umdNamedDefine) 4, set the agent chainWebpack: config => { config.devServer.port(8888) .open(true) .proxy({'/dev': { target: 'http://123.57.153.106:8080/', changeOrigin: true, pathRewrite: {' ^ / dev ': } // config.devserver.bonjour (bonjour).clientLogLevel(clientLogLevel).color(color) .compress(compress) .contentBase(contentBase) .disableHostCheck(disableHostCheck) .filename(filename) .headers(headers) .historyApiFallback(historyApiFallback) .host(host) .hot(hot) .hotOnly(hotOnly) .https(https) .inline(inline) .info(info) .lazy(lazy) .noInfo(noInfo) .open(open) .openPage(openPage) .overlay(overlay) .pfx(pfx) .pfxPassphrase(pfxPassphrase) .port(port) .progress(progress) .proxy(proxy) .public(public) .publicPath(publicPath) .quiet(quiet) .setup(setup) .socket(socket) .staticOptions(staticOptions) .stats(stats) .stdin(stdin) .uselocalip (useLocalIp).watchContentBase(watchContentBase).watchOptions(watchOptions) etcCopy the code

For configuration, see webPack Chinese official website

At this point, you’ll find that NPM Run Serve is accessible in the browser again.

In fact, I only have a superficial understanding of Webpack. After all, it is never too late to learn, and normal operation is to search and look at it when using it, and then forget it when not using it.

In this case, then we can write our component library.

Write and test your first component

In the previous chapter, we discussed how to create a component library project. Talked about vuE-CLI3.0 build project, and modify the directory folder. Add new vue.config.js to run the whole project. Now that we’re done with the preparation, let’s write our first component.

Mc-btn button assembly

Anyone who has written code knows that the button component is the most commonly used and the one best implemented.

Step 1 Create a folder named BTN in the Packages directory

Step 2 Create a folder named SRC under the BTN folder

3. Create a single file component named btn.vue in the SRC folder. content

<! --bnt.vue--> <template> <span class="mc-btn" @click="handleClick"> <slot></slot> </span> </template> <script> export Default {name: 'McBtn', // this name is important data () {return {}}, methods: { handleClick () { this.$emit('handleClick') } } } </script> <style lang="scss" scoped> .mc-btn { display: inline-block; width: 100px; height: 50px; line-height: 50px; border-radius: 4px; font-size: 4px; text-align: center; background: #09aeaf; color: white; } </style>Copy the code

Step 4 Create index.js under “./package/ BTN”

Import McBtn from './ SRC/BTN '// Provides the install method for components to import as required // All components must have install, Use () McBtn.install = Vue => {Vue.component(McBtn.name, McBtn)} export default McBtnCopy the code

This step exposes the component. Note that the component must have install before it can be used by vue.use (xx).

Step 5 create index.js under “/packages”

import McBtn from './btn'; // Define a list of components to put McBtn components into const Components = [McBtn //... future components need to be introduced at the beginning] // define the loader method that calls vUE, Const install = function (Vue) {if (install.installed) return install.installed = true // Component.map (Component => Vue.component(component.name, component))} If (Typeof Window! == 'undefined' && window.Vue) { install(window.Vue) } export default { install, ... components }Copy the code

The implication of this step is to load all components, which must be declared, then loaded in the component list, and then looped through the loader.

The main effect is to uniformly export all components and expose the install method. Instead of installing individual components within a component, the index.js component now installs all components in a loop, giving the user the option to load on demand or at once.

Well, at this point, a Btn component is written. The current directory structure is

Test the written Mc-btn component

The component is already written, so let’s try it out. We will first import the package we just wrote in main.js under examples, as follows:

import App from './App.vue' //... import McUI from "./.. /packages"; Vue.use(McUI); / /... Vue.config.productionTip = falseCopy the code

This step is introduced globally when the file is written locally

NPM install sass-loader node-sass NPM run serveCopy the code

This piece of special error special processing bar!

Step 2: Delete helloWord. vue and modify it in app.vue

    <template>
    <div id="app">
        <img alt="Vue logo" src="./assets/logo.png">
        <mc-test></mc-test>
    </div>
    </template>

    <script>


    export default {
    name: 'App',

    }
    </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>

Copy the code

Refresh the page and you can see that the page has changed

At this point, our Mc-btn component from development to testing is initially completed.

packaging

Vue-cli3 gives us a command line to build the target library:

vue-cli-service build --target lib --name xxx --dest lib [entry]

– target: indicates the build target. The default mode is application mode. Here change to lib to enable library mode.

– Dest: output directory, dist by default. So let’s change this to lib

[Entry]: entry file. The default value is SRC/app.vue.

Here we specify compile packages/ component library directory.

In the current package.json

/ /... "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint", "lib": "vue-cli-service build --target lib --name mch-ui --dest lib packages/index.js" }, "dependencies": { //... "lib": "vue-cli-service build --target lib --name mch-ui --dest lib packages/index.js"Copy the code

At this point, the new packaging command is configured, executenpm run libWait for the end of packing, you will find a directory folder under the morelibFolder.

So this lib folder is the package we want to publish to NPM.

release

All we need is a launch!

Sign up, log in, and get ready to publish directly from https://www.npmjs.com/.

NPM account contains three parts: username, password and email are the username, password and email respectively. After registering, you need to log in your email for verification, and then NPM publish can be verified. If it is an unverified email, 403 error will be reported when you publish.

Key points to pay attention to:

1. First of all, the name should not be repeated. Originally, I wanted to call Mc-ui, but I kept giving me a similar name that kept requiring me to change the name

2. Write the user name and password correctly

3, other package issues, please baidu, Google is also ok!

Finally, after many hardships, finally sent a McH-ui package. So ask on the spot to verify the effect.

McH-ui verification: Added (╯^╰ ╮)

CD to an empty folder and create a new Vue project using vue create Test

2,npm i mch-ui -S Import the McH-ui component library. When this step is done, you’ll notice that node_modules has an additional McH-ui folder that looks like this.Seeing lib means our component library is working and ready to reference.

3. Create main.js in the SRC folder of the test project

        import MCUI from "mch-ui";
        import 'mch-ui/lib/mch-ui.css'
        Vue.use(MCUI)

Copy the code

This is the global import component library

SRC components/ hellowold. vue

/ /... < the template > < div class = "hello" > < h1 > {{MSG}} < / h1 > < MC - BTN > this is a button < / MC - BTN > < / div > < / template > / /...Copy the code

5, perform

    npm i
    npm run serve
Copy the code

Open your browser and find:

At the end

The first step of the long march is to step out at last, the subsequent free play, DIY all kinds of their own component library.

If you feel you can, you can bookmark this page, or you can directly give McH-ui github source, a star

Official document: MCUI