今年三月份入職以來,一直在作後臺運營系統,其中重複性工做有不少,其中組件庫就是一項。儘管現階段有不少優秀的開源組件庫,可是爲了適應產品奇奇怪怪的需求,仍是要手動實現一些組件。將其沉澱下來,積累一些本身東西。javascript
概述:首先基於Vue-cli腳手架改裝一個組件庫的基本構建工具,它具有如下幾點功能:css
2018年12月25日新增html
將以前的v-highlight
指令vue
// 這樣加載了highlight全部的代碼語言包,有300kb+
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
hljs.configure({ useBR: true })
Vue.directive('highlight',function (el) {
let blocks = el.querySelectorAll('code')
blocks.forEach(block => {
hljs.highlightBlock(block)
})
})
複製代碼
修改成java
import hljs from 'highlight.js/lib/highlight';
import 'highlight.js/styles/github.css';
// 只加載Html、JavaScript
import javascript from 'highlight.js/lib/languages/javascript';
import xml from 'highlight.js/lib/languages/xml';
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('xml', xml);
Vue.directive('highlight', function (el) {
let blocks = el.querySelectorAll('code')
Array.prototype.forEach.call(blocks, block => {
hljs.highlightBlock(block)
})
})
複製代碼
安裝jscpd,npm i --save-dev jscpd
,修改packjson.jsonnode
{
....
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
// 添加
"check": "jscpd src",
"build": "node build/build.js"
},
...
}
複製代碼
運行結果webpack
代碼地址:UI-Library codegit
環境:win-64位、node-v8.12.0github
安裝web
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')
}
}
複製代碼
引入 sass-resources-loader
處理公共css文件
npm install -D sass-resources-loader --save-dev
修改上述 return
的值爲
{
...
scss: generateLoaders('sass').concat({
loader: 'sass-resources-loader',
options: {
resources: path.resolve(__dirname, '../src/assets/styles/common.scss')
}
})
...
}
複製代碼
因爲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)
})
})
複製代碼
利用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
]
}
)
複製代碼
往期文章:
原創聲明: 該文章爲原創文章,轉載請註明出處。