从零实现Vue的组件库(零)-基本结构以及构建工具

综合技术 2018-12-09 阅读原文

今年三月份入职以来,一直在做后台运营系统,其中重复性工作有很多,其中组件库就是一项。尽管现阶段有很多优秀的开源组件库,但是为了适应产品奇奇怪怪的需求,还是要手动实现一些组件。将其沉淀下来,积累一些自己东西。

概述:首先基于Vue-cli脚手架改装一个组件库的基本构建工具,它具备以下几点功能:

  • webpack3.0 升级 webpack4.0 => 更好地完成组件的开发以及打包工作;
  • 支持sass => 加速组件样式开发;
  • 支持导入markdown以及markdown样式自定义、以及code高亮;
  • 自动配置路由。

1. 实例

实例地址:[Fat-Ge UI library](http://fatge.xyz/blog/juejin-example-3#/)

代码地址:[UI-Library code](https://github.com/FatGe/UI-Library)
复制代码

2. 安装流程

环境:win-64位、node-v8.12.0

  • 安装

    npm install --global vue-cli

    安装vue-cli,之后创建一个ui-library的项目

    vue init webpack ui-library

    创建的项目的package.json中,webpack的版本为3.6.0

    "webpack": "^3.6.0",
    "webpack-bundle-analyzer": "^2.9.0",
    "webpack-dev-server": "^2.9.1",
    "webpack-merge": "^4.1.0"
    复制代码

    为了升级webpack4.1.2,先把当前webpack以及其相关依赖uninstall

    npm uninstall -D webpack webpack-bundle-analyzer webpack-dev-server webpack-merge
    npm uninstall -D copy-webpack-plugin css-loader eslint-loader file-loader html-webpack-plugin url-loader  friendly-errors-webpack-plugin optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin vue-loader
    复制代码

    安装webpack4,由于webpack4依赖webpack-cli,所以也需要安装

    npm install -D webpack webpack-cli webpack-bundle-analyzer webpack-dev-server webpack-merge
    npm install -D copy-webpack-plugin css-loader eslint-loader file-loader html-webpack-plugin url-loader  friendly-errors-webpack-plugin optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin vue-loader
    复制代码

    手动替换 extract-text-webpack-plugin
    插件 npm uninstall -D extract-text-webpack-plugin
    替换为 npm install -D mini-css-extract-plugin

    安装sass相关依赖 npm install -D node-sass sass-loader --save-dev

  • 配置

    • 首先配置webpack的mode,在webpack.dev.conf.js以及webpack.prod.conf.js中分别加上

      const devWebpackConfig = merge(baseWebpackConfig, {
          mode: 'production',
          ...
      })
      复制代码
      const webpackConfig = merge(baseWebpackConfig, {
          mode: 'development',
          ...
      })
      复制代码
    • 配置webpack.base.conf.js文件

      // 引入VueLoaderPlugin
      const { VueLoaderPlugin } = require('vue-loader')
      // 添加至
      const devWebpackConfig = merge(baseWebpackConfig, {
          ...
          plugins: [
              new VueLoaderPlugin(),
              ...
          ]
      })
      复制代码
    • 配置webpack.prod.conf.js文件

      需要删除


      const ExtractTextPlugin = require('extract-text-webpack-plugin')


      const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

      之后配置config项

      const ExtractTextPlugin = require('extract-text-webpack-plugin')
      const { VueLoaderPlugin } = require('vue-loader')
      
      const webpackConfig = merge(baseWebpackConfig, {
          optimization: {
              splitChunks: {
                cacheGroups: {
                  vendors: {
                    test: /[\/]node_modules[\/]/,
                    chunks: 'initial',
                    name: 'vendors',
                  },
                  'async-vendors': {
                    test: /[\/]node_modules[\/]/,
                    minChunks: 2,
                    chunks: 'async',
                    name: 'async-vendors'
                  }
                }
              },
              runtimeChunk: { name: 'runtime' }
          },
          plugins: [
              // 添加VueLoaderPlugin
              new VueLoaderPlugin(),
              ...
              // 引入MiniCssExtractPlugin
              new MiniCssExtractPlugin({
                filename: utils.assetsPath('css/[name].[contenthash:7].css')
              }),
              // Compress extracted CSS. We are using this plugin so that possible
              // duplicated CSS from different components can be deduped.
              new OptimizeCSSPlugin({
                cssProcessorOptions: config.build.productionSourceMap
                  ? { safe: true, map: { inline: false } }
                  : { safe: true }
              }),
              // see https://github.com/ampedandwired/html-webpack-plugin
              new HtmlWebpackPlugin({
                filename: config.build.index,
                template: 'index.html',
                inject: true,
                minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeAttributeQuotes: true
                  // more options:
                  // https://github.com/kangax/html-minifier#options-quick-reference
                },
                // necessary to consistently work with multiple chunks via CommonsChunkPlugin
                chunksSortMode: 'dependency'
              }),
              // keep module.id stable when vendor modules does not change
              new webpack.HashedModuleIdsPlugin(),
              // copy custom static assets
              new CopyWebpackPlugin([
                {
                  from: path.resolve(__dirname, '../static'),
                  to: config.build.assetsSubDirectory,
                  ignore: ['.*']
                }
              ])
          ]
      复制代码
    • 修改utils.js

      exports.cssLoaders = function(options) {
          options = options || {}
      
          // generate loader string to be used with extract text plugin
          function generateLoaders(loader, loaderOptions) {
              let loaders = []
              if (loader) {
                  loaders = [{
                      loader: loader + '-loader',
                      options: Object.assign({}, loaderOptions, {
                          sourceMap: options.sourceMap
                      })
                  }]
              }
      
              if (options.extract) {
                  let extractLoader = {
                      loader: MiniCssExtractPlugin.loader,
                      options: {}
                  }
      
                  return [extractLoader, 'css-loader'].concat(['postcss-loader'], loaders)
              } else {
      
                  return ['vue-style-loader', 'css-loader'].concat(['postcss-loader'], loaders)
              }
          }
      
          return {
              css: generateLoaders(),
              postcss: generateLoaders(),
              less: generateLoaders('less'),
              sass: generateLoaders('sass', { indentedSyntax: true }),
              scss: generateLoaders('sass'),
              stylus: generateLoaders('stylus'),
              styl: generateLoaders('stylus')
          }
      }
      复制代码

3. 支持导入markdown以及markdown样式自定义

由于 vue-markdown-loader
与vue-loader版本15有兼容性的问题,所以利用 text-loader
将Markdown文档导入并生成String,再编译为markdown文档。

首先 npm install -D text-loader
安装text-loader,用来引入*.md文件,再修改webpack.base.conf.js文件,添加text-loader

rules: [
    ...(config.dev.useEslint ? [createLintingRule()] : []),
    {
        test: /.md$/,
        loader: 'text-loader'
    },
    ...
]
复制代码

在引入 marked
对导入的String进行编译

<template>
    <div class="markdown-body" v-html="compiledMarkdown" v-highlight></div>
</template>

import markdown from '../../README.md'
import marked from 'marked'

export default {
  computed: {
    markdowonText () {
      // 编译markdown
      return marked(markdown)
    }
  }
}
复制代码

觉得markdown的样式有些丑,可以导入 github-markdown-css

npm install -D github-markdown-css

对样式进行修改。如果markdown中存在着某些code,可以通过 highlight
进行高亮展示

npm install -D highlight

import hljs from 'highlight.js'
// 调整高亮code的样式
import 'highlight.js/styles/vs2015.css'

hljs.configure({ useBR: true })
// 注册一个directive用来添加code高亮
Vue.directive('highlight',function (el) {
    let blocks = el.querySelectorAll('code')

    blocks.forEach(block => {
        hljs.highlightBlock(block)
    })
})
复制代码

4. 自动配置路由

利用 require.context
解析某个目录下的文件,将其生成Router的配置

const context = require.context('@/components/', true, /demo.vue$/)
const componentRouters = context.keys().map(url => {
    const start = url.indexOf('/')
    const end = url.lastIndexOf('/')
    const name = url.substring(start + 1, end)
    const path = `/${name}`
    
    return {
        name,
        path,
        component: require(`@/components${path}/demo`).default
    }
})

export default new Router({
    routes: [
        {
            path: '/',
            name: 'mainPage',
            component: mainPage
        },
        
        ...componentRouters
        ]
    }
)
复制代码
稀土掘金

责编内容by:稀土掘金阅读原文】。感谢您的支持!

您可能感兴趣的

Functional CSS: 从试着改进可重用CSS做起 从试着改进可重用CSS做起 泊学4K学习视频 回想起每次更新泊学网站,最让我头疼的,就是改写CSS。在不同的阶段,对CSS不断深入的理解,对网站内容的调整,对UI的重用需求,都影响着CSS的编写方式,因此,稍不留神,你的代码理...
Simple Vuejs tab To make a simple VueJS tab that does not need any library just a few lines of html and VueJS First of you create y...
CSS Hover different on/off transition Please can somebody explain the following. I believe that a transition can be triggered by, for example, hovering. M...
Cut a CSS transition short? I'm applying a CSS transition to an element. target.style.transition = "color 10000ms ease"; target.style.color =...
vue实现城市列表选择 成果展示 最后的成果就是下面所展示的内容,因为gif图没有做,只能截图所展示,接下来,会带着大家一步一步的完成下面功能,脚手架搭建和node安装在本次案例不会讲解,如果了解,可以在我的博客园找到有详细介绍 ...