kbone 能夠滿足大多數(shù)常見的開發(fā)場(chǎng)景,但是當(dāng)遇到當(dāng)前 dom/bom 接口不能滿足的情況時(shí),kbone 也提供了一系列 API 來(lái)擴(kuò)展 dom/bom 對(duì)象和接口。
這里需要注意的是,下述所有對(duì)于 dom/bom 對(duì)象的擴(kuò)展都是針對(duì)所有頁(yè)面的,也就是說有一個(gè)頁(yè)面對(duì)其進(jìn)行了擴(kuò)展,所有頁(yè)面都會(huì)生效,因此在使用擴(kuò)展時(shí)建議做好處理標(biāo)志,然后判斷是否已經(jīng)被擴(kuò)展過。
1、用法
1.1 使用 window.$$extend 對(duì) dom/bom 對(duì)象追加屬性/方法
舉個(gè)例子,假設(shè)需要對(duì) window.location 對(duì)象追加一個(gè)屬性 testStr 和一個(gè)方法 testFunc,可以編寫如下代碼:
window.$$extend('window.location', {
testStr: 'I am location',
testFunc() {
return `Hello, ${this.testStr}`
},
})
這樣便可以通過 window.location.testStr 獲取新追加的屬性,同時(shí)可以通過 window.location.testFunc() 調(diào)用新追加的方法。
1.2 使用 window.$$getPrototype 獲取 dom/bom 對(duì)象的原型
如果遇到追加屬性和追加方法都無(wú)法滿足需求的情況下,可以獲取到對(duì)應(yīng)對(duì)象的原型進(jìn)行操作:
const locationPrototype = window.$$getPrototype('window.location')
如上例子,locationPrototype 便是 window.location 對(duì)象的原型。
1.3 對(duì) dom/bom 對(duì)象方法追加前置/后置處理
除了上述的給對(duì)象新增和覆蓋方法,還可以對(duì)已有的方法進(jìn)行前置/后置處理。
前置處理即表示此方法會(huì)在執(zhí)行原始方法之前執(zhí)行,后置處理則是在之后執(zhí)行。前置處理方法接收到的參數(shù)和原始方法接收到的參數(shù)一致,后置處理方法接收到的參數(shù)則是原始方法執(zhí)行后返回的結(jié)果。下面給一個(gè)簡(jiǎn)單的例子:
const beforeAspect = function(...args) {
// 在執(zhí)行 window.location.testFunc 前被調(diào)用,args 為調(diào)用該方法時(shí)傳入的參數(shù)
}
const afterAspect = function(res) {
// 在執(zhí)行 window.location.testFunc 后被調(diào)用,res 為該方法返回結(jié)果
}
window.$$addAspect('window.location.testFunc.before', beforeAspect)
window.$$addAspect('window.location.testFunc.after', afterAspect)
window.location.testFunc('abc', 123) // 會(huì)執(zhí)行 beforeAspect,再調(diào)用 testFunc,最后再執(zhí)行 afterAspect
PS:具體 API 可參考 dom/bom 擴(kuò)展 API 文檔。
2、案例
在 kbone-advanced 目錄下創(chuàng)建 07-extend-dom-bom 目錄,本案例在這個(gè)目錄下完成。
2.1 創(chuàng)建 package.json
cd 07-extend-dom-bom
npm init -y
編輯 package.json:
{
"name": "07-extend-dom-bom",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "rimraf dist/web && cross-env NODE_ENV=production webpack --config build/webpack.config.js --progress --hide-modules",
"mp": "cross-env NODE_ENV=production webpack --config build/webpack.mp.config.js --progress --hide-modules"
},
"dependencies": {
"add": "^2.0.6",
"vue": "^2.5.11"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"cross-env": "^5.0.5",
"css-loader": "^0.28.7",
"file-loader": "^1.1.4",
"html-webpack-plugin": "^4.0.0-beta.5",
"mini-css-extract-plugin": "^0.5.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"stylehacks": "^4.0.3",
"vue-loader": "^15.7.0",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
"mp-webpack-plugin": "latest"
},
"keywords": [],
"author": "",
"license": "ISC"
}
安裝依賴包:
npm install
2.2 配置 webpack
在 07-extend-dom-bom/build 目錄下創(chuàng)建 webpack.mp.config.js,內(nèi)容如下:
const path = require('path')
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin')
const MpPlugin = require('mp-webpack-plugin') // 用于構(gòu)建小程序代碼的 webpack 插件
const isOptimize = false // 是否壓縮業(yè)務(wù)代碼,開發(fā)者工具可能無(wú)法完美支持業(yè)務(wù)代碼使用到的 es 特性,建議自己做代碼壓縮
module.exports = {
mode: 'production',
entry: {
app: path.resolve(__dirname, '../src/main.mp.js'),
page1: path.resolve(__dirname, '../src/page1/main.mp.js')
},
output: {
path: path.resolve(__dirname, '../dist/mp/common'), // 放到小程序代碼目錄中的 common 目錄下
filename: '[name].js', // 必需字段,不能修改
library: 'createApp', // 必需字段,不能修改
libraryExport: 'default', // 必需字段,不能修改
libraryTarget: 'window', // 必需字段,不能修改
},
target: 'web', // 必需字段,不能修改
optimization: {
runtimeChunk: false, // 必需字段,不能修改
splitChunks: { // 代碼分隔配置,不建議修改
chunks: 'all',
minSize: 1000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 100,
maxInitialRequests: 100,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
minimizer: isOptimize ? [
// 壓縮CSS
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.(css|wxss)$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', {
discardComments: {
removeAll: true,
},
minifySelectors: false, // 因?yàn)?wxss 編譯器不支持 .some>:first-child 這樣格式的代碼,所以暫時(shí)禁掉這個(gè)
}],
},
canPrint: false
}),
// 壓縮 js
new TerserPlugin({
test: /\.js(\?.*)?$/i,
parallel: true,
})
] : [],
},
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
],
},
{
test: /\.vue$/,
loader: [
'vue-loader',
],
},
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
},
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
extensions: ['*', '.js', '.vue', '.json']
},
plugins: [
new webpack.DefinePlugin({
'process.env.isMiniprogram': true, // 注入環(huán)境變量,用于業(yè)務(wù)代碼判斷
}),
new MiniCssExtractPlugin({
filename: '[name].wxss',
}),
new VueLoaderPlugin(),
new MpPlugin(require('./miniprogram.config.js')),
],
}
在 07-extend-dom-bom/build 目錄下創(chuàng)建 miniprogram.config.js,內(nèi)容如下:
module.exports = {
origin: 'https://test.miniprogram.com',
entry: '/',
router: {
page1: ['/a']
},
redirect: {
notFound: 'page1',
accessDenied: 'page1',
},
generate: {
// 構(gòu)建完成后是否自動(dòng)安裝小程序依賴。'npm':使用 npm 自動(dòng)安裝依賴
autoBuildNpm: 'npm'
},
app: {
navigationBarTitleText: 'miniprogram-project',
},
global: {
share: true,
rem: true
},
projectConfig: {
appid: '',
projectname: 'miniprogram-project',
},
packageConfig: {
author: 'Felixlu',
}
}
2.3 創(chuàng)建入口頁(yè)面
在 /src/ 下創(chuàng)建 main.mp.js 文件,內(nèi)容如下:
import Vue from 'vue'
import App from './App'
export default function createApp() {
const container = document.createElement('div')
container.id = 'app'
document.body.appendChild(container)
// 例子一:使用 window.$$extend 對(duì) dom/bom 對(duì)象追加屬性/方法
window.$$extend('window.location', {
testStr: 'I am location',
testFunc() {
console.log(`Hello, ${this.testStr}`)
},
})
// 例子二:使用 window.$$getPrototype 獲取 dom/bom 對(duì)象的原型
const locationPrototype = window.$$getPrototype('window.location')
console.log(locationPrototype)
// 例子三:對(duì) dom/bom 對(duì)象方法追加前置/后置處理
const beforeAspect = function(...args) {
// 在執(zhí)行 window.location.testFunc 前被調(diào)用,args 為調(diào)用該方法時(shí)傳入的參數(shù)
console.log('執(zhí)行 window.location.testFunc 前')
}
const afterAspect = function(res) {
// 在執(zhí)行 window.location.testFunc 后被調(diào)用,res 為該方法返回結(jié)果
console.log('執(zhí)行 window.location.testFunc 后')
}
window.$$addAspect('window.location.testFunc.before', beforeAspect)
window.$$addAspect('window.location.testFunc.after', afterAspect)
return new Vue({
el: '#app',
render: h => h(App)
})
}
在 /src/ 下創(chuàng)建 App.vue 文件,內(nèi)容如下:
<template>
<div>
我是 page1 頁(yè)面。
</div>
</template>
<script>
export default {
mounted() {
window.location.testFunc()
}
}
</script>
2.4 創(chuàng)建 page1 相關(guān)文件
在 /src/page1 下創(chuàng)建 main.mp.js 文件,內(nèi)容如下:
import Vue from 'vue'
import App from './App.vue'
export default function createApp() {
const container = document.createElement('div')
container.id = 'app'
document.body.appendChild(container)
return new Vue({
el: '#app',
render: h => h(App)
})
}
在 /src/page1 下創(chuàng)建 App.vue 文件,內(nèi)容如下:
<template>
<div>
我是 page1 頁(yè)面。
</div>
</template>
<script>
export default {
mounted() {
window.location.testFunc()
}
}
</script>
2.5 小程序端效果預(yù)覽
npm run mp
主頁(yè)面:
點(diǎn)擊“進(jìn)入page1頁(yè)面”: