提交 cb1435d6 编写于 作者: fxy060608's avatar fxy060608

refactor(cli): plugin

上级 044b4399
const fs = require('fs')
const path = require('path')
function getTemplatePath(template) {
if (template) {
return path.resolve(process.env.UNI_INPUT_DIR, template)
}
return path.resolve(process.env.UNI_CLI_CONTEXT, 'public/index.html')
}
function transform(content) {
if (process.env.NODE_ENV === 'production') {
return content + // shadow
`body::after{position:fixed;content:'';left:-1000px;top:-1000px;-webkit-animation:shadow-preload .1s;-webkit-animation-delay:3s;animation:shadow-preload .1s;animation-delay:3s}@-webkit-keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}@keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}`
}
return content
}
function getIndexCssPath(assetsDir, template) {
const VUE_APP_INDEX_CSS_HASH = process.env.VUE_APP_INDEX_CSS_HASH
if (VUE_APP_INDEX_CSS_HASH) {
try {
const templateContent = fs.readFileSync(getTemplatePath(template))
if (/\bVUE_APP_INDEX_CSS_HASH\b/.test(templateContent)) {
return path.join(assetsDir, `[name].${VUE_APP_INDEX_CSS_HASH}.[ext]`)
}
} catch (e) {}
}
return assetsDir
}
module.exports = {
options: {
cssVars: {
'--status-bar-height': '0px'
},
filterTag: 'wxs',
vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue'
},
copyWebpackOptions(platformOptions, vueOptions) {
return [{
from: require.resolve('@dcloudio/uni-h5/dist/index.css'),
to: getIndexCssPath(vueOptions.assetsDir, platformOptions.template),
transform
},
'hybrid/html'
]
}
}
......@@ -4,7 +4,7 @@
"scripts": {
"build:service:legacy": "npm run lint && rollup -c build/rollup.config.service.js",
"lint": "eslint --fix --config package.json --ext .js --ext .vue --ignore-path .eslintignore build src",
"lint:cli": "eslint --fix --config package.json --ext .js --ext .vue --ignore-path .eslintignore packages/uni-cli-shared packages/uni-template-compiler \"packages/vue-cli-*/**/*.js\" \"packages/webpack-uni-*/**/*.js\"",
"lint:cli": "eslint --fix --config package.json --ext .js --ext .vue --ignore-path .eslintignore packages/uni-cli-shared packages/uni-template-compiler \"packages/uni-*/lib/*.js\" \"packages/vue-cli-*/**/*.js\" \"packages/webpack-uni-*/**/*.js\"",
"dev:h5": "npm run lint && cross-env NODE_ENV=production UNI_WATCH=true UNI_PLATFORM=h5 node build/build.js",
"build:h5": "npm run lint && cross-env NODE_ENV=production UNI_WATCH=false UNI_PLATFORM=h5 node build/build.js",
"build:h5:ui": "cross-env NODE_ENV=production UNI_WATCH=false UNI_PLATFORM=h5 UNI_UI=true node build/build.js",
......
const fs = require('fs')
const path = require('path')
const COMPONENTS_DIR_NAME = 'wxcomponents'
function getComponentsCopyOption () {
if (process.env.UNI_OUTPUT_TMP_DIR) { // TODO v3不需要,即将废弃
const componentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME)
if (fs.existsSync(componentsDir)) {
return {
from: componentsDir,
to: COMPONENTS_DIR_NAME,
ignore: ['**/*.vue', '**/*.css']
}
}
}
}
module.exports = {
options: {
extnames: { // TODO v3不需要此配置
style: '.wxss',
template: '.wxml',
filter: '.wxs'
},
filterTag: 'wxs'
},
copyWebpackOptions (platformOptions, vueOptions) {
const copyOptions = []
const componentsCopyOption = getComponentsCopyOption()
if (componentsCopyOption) {
copyOptions.push(componentsCopyOption)
}
copyOptions.push('hybrid/html')
if (process.env.UNI_USING_V3) { // TODO 将仅保留v3逻辑
copyOptions.push(path.resolve(__dirname, '../dist/view.css'))
copyOptions.push(path.resolve(__dirname, '../dist/view.umd.min.js'))
// TODO 后续common与v3目录应该合并
copyOptions.push(path.resolve(__dirname, '../template/common'))
copyOptions.push(path.resolve(__dirname, '../template/v3'))
}
return copyOptions
}
}
{
"name": "@dcloudio/uni-app-plus",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app app-plus",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-plus"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-app-plus",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app app-plus",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-app-plus"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"uni-app": {
"name": "app-plus",
"title": "APP-PLUS"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
此差异已折叠。
!function(e){var t={};function n(a){if(t[a])return t[a].exports;var o=t[a]={i:a,l:!1,exports:{}};return e[a].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(a,o,function(t){return e[t]}.bind(null,o));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=43)}([function(e,t){e.exports={}},function(e,t,n){"use strict";function a(e,t,n,a,o,r,i,s,c,u){var l,f="function"==typeof e?e.options:e;if(c&&(f.components=Object.assign(c,f.components||{})),u&&((u.beforeCreate||(u.beforeCreate=[])).unshift(function(){this[u.__module]=this}),(f.mixins||(f.mixins=[])).push(u)),t&&(f.render=t,f.staticRenderFns=n,f._compiled=!0),a&&(f.functional=!0),r&&(f._scopeId="data-v-"+r),i?(l=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),o&&o.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},f._ssrRegister=l):o&&(l=s?function(){o.call(this,this.$root.$options.shadowRoot)}:o),l)if(f.functional){f._injectStyles=l;var d=f.render;f.render=function(e,t){return l.call(t),d(e,t)}}else{var p=f.beforeCreate;f.beforeCreate=p?[].concat(p,l):[l]}return{exports:e,options:f}}n.d(t,"a",function(){return a})},function(e,t,n){"use strict";var a;Object.defineProperty(t,"__esModule",{value:!0}),t.weexPlus=t.default=void 0,a="function"==typeof getUni?getUni:function(){var e=function(e){return"function"==typeof e},t=/^\$|^on|^create|Sync$|Manager$|^pause/,n=["os","getCurrentSubNVue","getSubNVueById","stopRecord","stopVoice","stopBackgroundAudio","stopPullDownRefresh","hideKeyboard","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","canIUse","navigateBack","closeSocket","pageScrollTo","drawCanvas"],a=function(e){return!(t.test(e)&&"createBLEConnection"!==e||~n.indexOf(e))},r=function(t){return function(){for(var n=arguments.length,a=Array(n>1?n-1:0),o=1;o<n;o++)a[o-1]=arguments[o];var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e(r.success)||e(r.fail)||e(r.complete)?t.apply(void 0,[r].concat(a)):new Promise(function(e,n){t.apply(void 0,[Object.assign({},r,{success:e,fail:n})].concat(a)),Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(n){return t.resolve(e()).then(function(){return n})},function(n){return t.resolve(e()).then(function(){throw n})})}}).then(function(e){return[null,e]}).catch(function(e){return[e]})}},i=[],s=void 0;function c(e){i.forEach(function(t){return t({origin:s,data:e})})}var u=o.webview.currentWebview().id,l=new BroadcastChannel("UNI-APP-SUBNVUE");function f(e){e.$processed=!0;var t=o.webview.currentWebview().id===e.id,n="uniNView"===e.__uniapp_origin_type&&e.__uniapp_origin_id,a=e.id;if(e.postMessage=function(e){n?l.postMessage({data:e,to:t?n:a}):_({type:"UniAppSubNVue",data:e})},e.onMessage=function(e){i.push(e)},e.__uniapp_mask_id){s=e.__uniapp_host;var r=e.__uniapp_mask,c=o.webview.getWebviewById(e.__uniapp_mask_id);c=c.parent()||c;var u=e.show,f=e.hide,d=e.close,p=function(){c.setStyle({mask:"none"})};e.show=function(){c.setStyle({mask:r});for(var t=arguments.length,n=Array(t),a=0;a<t;a++)n[a]=arguments[a];return u.apply(e,n)},e.hide=function(){p();for(var t=arguments.length,n=Array(t),a=0;a<t;a++)n[a]=arguments[a];return f.apply(e,n)},e.close=function(){p();for(var t=arguments.length,n=Array(t),a=0;a<t;a++)n[a]=arguments[a];return d.apply(e,n)}}}function d(e){var t=o.webview.getWebviewById(e);return t&&!t.$processed&&f(t),t}l.onmessage=function(e){e.data.to===u&&c(e.data.data)};var p=weex.requireModule("plus"),g=weex.requireModule("globalEvent"),v=0,h={},y="__uniapp__service";g.addEventListener("plusMessage",function(e){"UniAppJsApi"===e.data.type?A(e.data.id,e.data.data):"UniAppSubNVue"===e.data.type?c(e.data.data,e.data.options):"onNavigationBarButtonTap"===e.data.type?"function"==typeof S&&S(e.data.data):"onNavigationBarSearchInputChanged"===e.data.type?"function"==typeof C&&C(e.data.data):"onNavigationBarSearchInputConfirmed"===e.data.type?"function"==typeof w&&w(e.data.data):"onNavigationBarSearchInputClicked"===e.data.type&&"function"==typeof E&&E(e.data.data)});var A=function(e,t){var n=h[e];n?(n(t),n.keepAlive||delete h[e]):console.error("callback["+e+"] is undefined")},m=function(t){var n,a,o=t.id,r=t.type,i=t.params;h[o]=(a=function(t){e(n)?n(t):n&&(~t.errMsg.indexOf(":ok")?e(n.success)&&n.success(t):~t.errMsg.indexOf(":fail")&&e(n.fail)&&n.fail(t),e(n.complete)&&n.complete(t))},(e(n=i)||n&&e(n.callback))&&(a.keepAlive=!0),a),p.postMessage({id:o,type:r,params:i},y)};function _(e){p.postMessage(e,y)}var b=function(e){return function(t){m({id:v++,type:e,params:t})}},S=void 0,C=void 0,w=void 0,E=void 0;function M(e){S=e}function k(e){C=e}function B(e){w=e}function O(e){E=e}function I(e){return weex.requireModule(e)}var N=weex.requireModule("dom"),P=weex.requireModule("globalEvent"),T=[];function D(e){"function"==typeof e&&(this.isUniAppReady?e():T.push(e))}P.addEventListener("plusMessage",function(e){"UniAppReady"===e.data.type&&(D.isUniAppReady=!0,T.length&&(T.forEach(function(e){return e()}),T=[]))});var x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},U=weex.requireModule("stream"),R="GET",V=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:R,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"application/x-www-form-urlencoded";return"object"===(void 0===e?"undefined":x(e))?"POST"===t.toUpperCase()&&"application/json"===n.toLowerCase()?JSON.stringify(e):Object.keys(e).map(function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])}).join("&"):e},F=weex.requireModule("plusstorage"),j="__TYPE",$=weex.requireModule("clipboard"),L=function(){if("function"==typeof getUniEmitter)return getUniEmitter;var e={$on:function(){console.warn("uni.$on failed")},$off:function(){console.warn("uni.$off failed")},$once:function(){console.warn("uni.$once failed")},$emit:function(){console.warn("uni.$emit failed")}};return function(){return e}}();function Q(e,t,n){return e[t].apply(e,n)}var J=Object.freeze({loadFontFace:function(t){var n=t.family,a=t.source,o=(t.desc,t.success),r=(t.fail,t.complete);N.addRule("fontFace",{fontFamily:n,src:a.replace(/"/g,"'")});var i={errMsg:"loadFontFace:ok",status:"loaded"};e(o)&&o(i),e(r)&&r(i)},ready:D,request:function(t){var n=t.url,a=t.data,o=t.header,r=t.method,i=void 0===r?"GET":r,s=t.dataType,c=void 0===s?"json":s,u=(t.responseType,t.success),l=t.fail,f=t.complete,d=!1,p=!1,g={};if(o)for(var v in o)p||"content-type"!==v.toLowerCase()?g[v]=o[v]:(p=!0,g["Content-Type"]=o[v]);return i===R&&a&&(n=n+(~n.indexOf("?")?"&"===n.substr(-1)||"?"===n.substr(-1)?"":"&":"?")+V(a)),U.fetch({url:n,method:i,headers:g,type:"json"===c?"json":"text",body:i!==R?V(a,i,g["Content-Type"]):""},function(t){var n=t.status,a=(t.ok,t.statusText,t.data),o=t.headers,r={};!n||-1===n||d?(r.errMsg="request:fail",e(l)&&l(r)):(r.data=a,r.statusCode=n,r.header=o,e(u)&&u(r)),e(f)&&f(r)}),{abort:function(){d=!0}}},getStorage:function(t){var n=t.key,a=(t.data,t.success),o=t.fail,r=t.complete;F.getItem(n+j,function(t){if("success"===t.result){var i=t.data;F.getItem(n,function(t){if("success"===t.result){var n=t.data;i&&n?("String"!==i&&(n=JSON.parse(n)),e(a)&&a({errMsg:"getStorage:ok",data:n})):(t.errMsg="setStorage:fail",e(o)&&o(t))}else t.errMsg="setStorage:fail",e(o)&&o(t);e(r)&&r(t)})}else t.errMsg="setStorage:fail",e(o)&&o(t),e(r)&&r(t)})},setStorage:function(t){var n=t.key,a=t.data,o=t.success,r=t.fail,i=t.complete,s="String";"object"===(void 0===a?"undefined":x(a))&&(s="Object",a=JSON.stringify(a)),F.setItem(n,a,function(t){"success"===t.result?F.setItem(n+j,s,function(t){"success"===t.result?e(o)&&o({errMsg:"setStorage:ok"}):(t.errMsg="setStorage:fail",e(r)&&r(t))}):(t.errMsg="setStorage:fail",e(r)&&r(t)),e(i)&&i(t)})},removeStorage:function(t){var n=t.key,a=(t.data,t.success),o=t.fail,r=t.complete;F.removeItem(n,function(t){"success"===t.result?e(a)&&a({errMsg:"removeStorage:ok"}):(t.errMsg="removeStorage:fail",e(o)&&o(t)),e(r)&&r(t)}),F.removeItem(n+j)},clearStorage:function(e){e.key,e.data,e.success,e.fail,e.complete},getClipboardData:function(t){var n=t.success,a=(t.fail,t.complete);$.getString(function(t){var o={errMsg:"getClipboardData:ok",data:t.data};e(n)&&n(o),e(a)&&a(o)})},setClipboardData:function(t){var n=t.data,a=t.success,o=(t.fail,t.complete),r={errMsg:"setClipboardData:ok"};$.setString(n),e(a)&&a(r),e(o)&&o(r)},onSubNVueMessage:c,getSubNVueById:d,getCurrentSubNVue:function(){return d(o.webview.currentWebview().id)},$on:function(){return Q(L(),"$on",[].concat(Array.prototype.slice.call(arguments)))},$off:function(){return Q(L(),"$off",[].concat(Array.prototype.slice.call(arguments)))},$once:function(){return Q(L(),"$once",[].concat(Array.prototype.slice.call(arguments)))},$emit:function(){return Q(L(),"$emit",[].concat(Array.prototype.slice.call(arguments)))}}),q={os:{nvue:!0}},K={};return"undefined"!=typeof Proxy?K=new Proxy({},{get:function(e,t){if("os"===t)return{nvue:!0};if("postMessage"===t)return _;if("requireNativePlugin"===t)return I;if("onNavigationBarButtonTap"===t)return M;if("onNavigationBarSearchInputChanged"===t)return k;if("onNavigationBarSearchInputConfirmed"===t)return B;if("onNavigationBarSearchInputClicked"===t)return O;var n=J[t];return n||(n=b(t)),a(t)?r(n):n}}):(Object.keys(q).forEach(function(e){K[e]=q[e]}),K.postMessage=_,K.requireNativePlugin=I,K.onNavigationBarButtonTap=M,K.onNavigationBarSearchInputChanged=k,K.onNavigationBarSearchInputConfirmed=B,K.onNavigationBarSearchInputClicked=O,Object.keys({uploadFile:!0,downloadFile:!0,chooseImage:!0,previewImage:!0,getImageInfo:!0,saveImageToPhotosAlbum:!0,chooseVideo:!0,saveVideoToPhotosAlbum:!0,saveFile:!0,getSavedFileList:!0,getSavedFileInfo:!0,removeSavedFile:!0,openDocument:!0,setStorage:!0,getStorage:!0,getStorageInfo:!0,removeStorage:!0,clearStorage:!0,getLocation:!0,chooseLocation:!0,openLocation:!0,getSystemInfo:!0,getNetworkType:!0,makePhoneCall:!0,scanCode:!0,setScreenBrightness:!0,getScreenBrightness:!0,setKeepScreenOn:!0,vibrateLong:!0,vibrateShort:!0,addPhoneContact:!0,showToast:!0,showLoading:!0,hideToast:!0,hideLoading:!0,showModal:!0,showActionSheet:!0,setNavigationBarTitle:!0,setNavigationBarColor:!0,navigateTo:!0,redirectTo:!0,reLaunch:!0,switchTab:!0,navigateBack:!0,getProvider:!0,login:!0,getUserInfo:!0,share:!0,requestPayment:!0,subscribePush:!0,unsubscribePush:!0,onPush:!0,offPush:!0}).forEach(function(e){var t=J[e];t||(t=b(e)),a(e)?K[e]=r(t):K[e]=t})),K};var o=new WeexPlus(weex);t.weexPlus=o;var r=a(weex,o,BroadcastChannel);t.default=r},function(e,t,n){Vue.prototype.__$appStyle__={},Vue.prototype.__merge_style&&Vue.prototype.__merge_style(n(4).default,Vue.prototype.__$appStyle__)},function(e,t,n){"use strict";n.r(t);var a=n(0),o=n.n(a);for(var r in a)"default"!==r&&function(e){n.d(t,e,function(){return a[e]})}(r);t.default=o.a},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={onLoad:function(){this.initMessage()},methods:{initMessage:function(){var t=this,n=e.webview.currentWebview().extras||{},a=n.from,o=(n.callback,n.runtime),r=n.data,i=void 0===r?{}:r,s=n.useGlobalEvent;this.__from=a,this.__runtime=o,this.__page=e.webview.currentWebview().id,this.__useGlobalEvent=s,this.data=JSON.parse(JSON.stringify(i)),e.key.addEventListener("backbutton",function(){"function"==typeof t.onClose?t.onClose():e.webview.currentWebview().close("auto")});var c=this,u=function(e){var t=e.data&&e.data.__message;t&&c.__onMessageCallback&&c.__onMessageCallback(t.data)};this.__useGlobalEvent?weex.requireModule("globalEvent").addEventListener("plusMessage",u):new BroadcastChannel(this.__page).onmessage=u},postMessage:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a={__message:{__page:this.__page,data:t,keep:n}},o=this.__from;if("v8"===this.__runtime){if(this.__useGlobalEvent)e.webview.postMessageToUniNView(a,o);else new BroadcastChannel(o).postMessage(a)}else{var r=e.webview.getWebviewById(o);r&&r.evalJS("__plusMessage&&__plusMessage(".concat(JSON.stringify({data:a}),")"))}},onMessage:function(e){this.__onMessageCallback=e}}};t.default=n}).call(this,n(2).weexPlus)},,,function(e,t,n){"use strict";var a=n(32),o=n(17),r=n(1);var i=Object(r.a)(o.default,a.b,a.c,!1,null,null,"57707442",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(38).default,this.options.style):Object.assign(this.options.style,n(38).default)}).call(i),t.default=i.exports},,,,,,,,,function(e,t,n){"use strict";var a=n(18),o=n.n(a);t.default=o.a},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a,o,r=(a=n(5))&&a.__esModule?a:{default:a};function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e.barcode,c={qrCode:[s.QR,s.AZTEC,s.MAXICODE],barCode:[s.EAN13,s.EAN8,s.UPCA,s.UPCE,s.CODABAR,s.CODE128,s.CODE39,s.CODE93,s.ITF,s.RSS14,s.RSSEXPANDED],datamatrix:[s.DATAMATRIX],pdf417:[s.PDF417]},u=(i(o={},s.QR,"QR_CODE"),i(o,s.EAN13,"EAN_13"),i(o,s.EAN8,"EAN_8"),i(o,s.DATAMATRIX,"DATA_MATRIX"),i(o,s.UPCA,"UPC_A"),i(o,s.UPCE,"UPC_E"),i(o,s.CODABAR,"CODABAR"),i(o,s.CODE39,"CODE_39"),i(o,s.CODE93,"CODE_93"),i(o,s.CODE128,"CODE_128"),i(o,s.ITF,"CODE_25"),i(o,s.PDF417,"PDF_417"),i(o,s.AZTEC,"AZTEC"),i(o,s.RSS14,"RSS_14"),i(o,s.RSSEXPANDED,"RSSEXPANDED"),o),l={mixins:[r.default],data:{filters:[0,2,1],backgroud:"#000000",frameColor:"#118ce9",scanbarColor:"#118ce9",enabledFlash:!1,flashImage0:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAABjklEQVRoQ+1ZbVHEQAx9TwE4ABTcOQAknANQAKcAUAAOAAXgAHAACsDCKQiTmbYDzJZtNt2bFrJ/m6+Xl2yyU2LmhzOPH/8PgIjcADirxNyapNoffMwMiMgzgMPBHmyCLySPLCoBwJKtAbJbYaBmD1yRvBwAtBMxl5DF+DZkiwCIyBLAzsgBbki+Wm2WAlCaL6zOMvKnJO+sNksB7ALQbO1ZHfbIv5FUVs2nCIB6EZETALdmj2mFY5I6X8ynGEADQllYmL1+VzBfnV/VvQB0aj45ARyQ/Ci14QLQsOBZLe5JaikWnzEA7AN4L4hgA2Dpyb76dANwsOCq/TZhASAYKGie0a7R1lDPI0ebtF0NUi+4yfdAtxr3PEMnD6BbD0QkNfACQO05EAwMuaBqDrIVycdmTpwDuP4R0OR7QFftVRP0g+49cwOQq4DJMxAAchmofY3m/EcJBQOZbTRKKJeBKKEoIePvpFRJ1VzmciUccyCa+C81cerBkuuB7sGTE/zt+yhN7AnAqxsAvBn06n8CkyPwMZKwm+UAAAAASUVORK5CYII=",flashImage1:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAMFBMVEUAAAA3kvI3lfY2k/VAl+43k/U3k/Q4k/M3kvI3k/M4k/Q4lPU2lPU2k/Vdq843k/WWSpNKAAAAD3RSTlMAwD+QINCAcPBgUDDgoBAE044kAAAAdklEQVQ4y2OgOrD/DwffUSTkERIfyZXAtOMbca7iVoKDDSgSbAijJqBI8J2HiX9FM2s+TOITmgQrTEIATYIJJuEA5mJ68S+Gg/0hEi0YEoxQK2gs0WyPQyKBGYeEAhPtJRaw45AIccXpwVEJekuwQyQWMFAfAACeDBJY9aXa3QAAAABJRU5ErkJggg=="},onLoad:function(){var e=this,t=this.data.scanType,n=[];Array.isArray(t)&&t.length&&t.forEach(function(e){var t=c[e];t&&(n=n.concat(t))}),n.length||(n=n.concat(c.qrCode).concat(c.barCode).concat(c.datamatrix).concat(c.pdf417)),this.filters=n,this.onMessage(function(t){e.gallery()})},onUnload:function(){this.cancel()},methods:{start:function(){this.$refs.barcode.start({conserve:!0,filename:"_doc/barcode/"})},scan:function(t){var n=this;s.scan(t,function(e,t,a){n.scanSuccess(e,t,a)},function(){e.nativeUI.toast("识别失败")},this.filters)},cancel:function(){this.$refs.barcode.cancel()},gallery:function(){var t=this;e.gallery.pick(function(e){t.scan(e)},function(t){12!==t.code&&e.nativeUI.toast("选择失败")},{multiple:!1,system:!1})},onmarked:function(e){var t=e.detail;this.scanSuccess(t.code,t.message,t.file)},scanSuccess:function(e,t,n){this.postMessage({event:"marked",detail:{scanType:u[e],result:t,charSet:"utf8",path:n||""}})},onerror:function(e){this.postMessage({event:"fail",message:JSON.stringify(e)})},setFlash:function(){this.enabledFlash=!this.enabledFlash,this.$refs.barcode.setFlash(this.enabledFlash)}}};t.default=l}).call(this,n(2).weexPlus)},function(e,t){e.exports={content:{flex:1,alignItems:"center",justifyContent:"center",backgroundColor:"#000000"},barcode:{position:"absolute",left:0,top:0,right:0,bottom:0,zIndex:1},"set-flash":{alignItems:"center",justifyContent:"center",transform:"translateY(80px)",zIndex:2},"image-flash":{width:"26",height:"26",marginBottom:"2"},"image-flash-text":{fontSize:"10",color:"#FFFFFF"}}},,,,,,,,,,,,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("scroll-view",{staticStyle:{flexDirection:"column"},attrs:{scrollY:!0,enableBackToTop:!0,bubble:"true"}},[n("view",{staticClass:["content"]},[n("barcode",{ref:"barcode",staticClass:["barcode"],attrs:{autostart:"true",backgroud:e.backgroud,frameColor:e.frameColor,scanbarColor:e.scanbarColor,filters:e.filters},on:{marked:e.onmarked,error:e.onerror}}),n("view",{staticClass:["set-flash"],on:{click:e.setFlash}},[n("u-image",{staticClass:["image-flash"],attrs:{src:e.enabledFlash?e.flashImage1:e.flashImage0,resize:"stretch"}}),n("u-text",{staticClass:["image-flash-text"]},[e._v(e._s(e.enabledFlash?"轻触关闭":"轻触照亮"))])],1)],1)])},o=[];n.d(t,"b",function(){return a}),n.d(t,"c",function(){return o}),n.d(t,"a",function(){})},,,,,,function(e,t,n){"use strict";n.r(t);var a=n(19),o=n.n(a);for(var r in a)"default"!==r&&function(e){n.d(t,e,function(){return a[e]})}(r);t.default=o.a},,,,,function(e,t,n){"use strict";n.r(t);n(3);var a=n(8);a.default.mpType="page",a.default.route="template/__uniappscan",a.default.el="#root",new Vue(a.default)}]);
\ No newline at end of file
此差异已折叠。
因为 它太大了无法显示 source diff 。你可以改为 查看blob
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<script>
var __UniViewStartTime__ = Date.now();
document.addEventListener('DOMContentLoaded', function() {
document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px'
})
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title>View</title>
<link rel="stylesheet" href="view.css" />
</head>
<body>
<div id="app"></div>
<script src="__uniappes6.js"></script>
<script src="view.umd.min.js"></script>
<script src="app-view.js"></script>
</body>
</html>
......@@ -40,7 +40,6 @@ const {
getPlatformProject,
isSupportSubPackages,
getPlatforms,
getPlatformGlobal,
getPlatformScss,
getPlatformSass,
runByHBuilderX,
......@@ -48,7 +47,6 @@ const {
isInHBuilderXAlpha,
getPlatformExts,
getPlatformTarget,
getPlatformVue,
getShadowCss,
getPlatformCssVars,
getPlatformCssnano,
......@@ -58,8 +56,7 @@ const {
htmlPreprocessOptions,
nvueJsPreprocessOptions,
nvueCssPreprocessOptions,
nvueHtmlPreprocessOptions,
devtoolModuleFilenameTemplate
nvueHtmlPreprocessOptions
} = require('./platform')
module.exports = {
......@@ -93,8 +90,6 @@ module.exports = {
getPlatformExts,
getPlatformTarget,
getPlatformProject,
getPlatformVue,
getPlatformGlobal,
getShadowCss,
getPlatformCssVars,
getPlatformCssnano,
......@@ -109,6 +104,5 @@ module.exports = {
htmlPreprocessOptions,
nvueJsPreprocessOptions,
nvueCssPreprocessOptions,
nvueHtmlPreprocessOptions,
devtoolModuleFilenameTemplate
nvueHtmlPreprocessOptions
}
......@@ -75,7 +75,7 @@ function getH5Options (manifestJson) {
if (!h5.publicPath.endsWith('/')) {
h5.publicPath = h5.publicPath + '/'
}
} else { // 其他模式,启用 base
} else { // 其他模式,启用 base
if (base.startsWith('./')) {
// 在开发模式, publicPath 如果为 './' webpack-dev-server 匹配文件时会失败
h5.publicPath = base.substr(1)
......@@ -90,6 +90,11 @@ function getH5Options (manifestJson) {
h5.devServer = h5.devServer || {}
// 插件修改 h5Options
global.uniPlugin.configureH5.forEach(configureH5 => {
configureH5(h5)
})
return h5
}
......@@ -98,4 +103,4 @@ module.exports = {
parseManifestJson,
getNetworkTimeout,
getH5Options
}
}
......@@ -2,7 +2,9 @@ const fs = require('fs')
const path = require('path')
const {
normalizePath
isInHBuilderX,
isInHBuilderXAlpha,
normalizeNodeModules
} = require('./util')
const {
......@@ -10,8 +12,6 @@ const {
SASS
} = require('./scss')
const uniRuntime = '@dcloudio/vue-cli-plugin-uni/packages/mp-vue'
function getShadowCss () {
let tagName = 'page'
if (process.env.UNI_PLATFORM === 'h5') {
......@@ -20,462 +20,21 @@ function getShadowCss () {
return `${tagName}::after{position:fixed;content:'';left:-1000px;top:-1000px;-webkit-animation:shadow-preload .1s;-webkit-animation-delay:3s;animation:shadow-preload .1s;animation-delay:3s}@-webkit-keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}@keyframes shadow-preload{0%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}100%{background-image:url(https://cdn.dcloud.net.cn/img/shadow-grey.png)}}`
}
function getCopyOption (file, options) {
if (file === 'wxcomponents') {
if (!options) {
options = {}
}
// 不拷贝vue,css(这些可能是 uni-migration 转换二来的)
options.ignore = ['**/*.vue', '**/*.css']
}
if (path.isAbsolute(file)) {
if (fs.existsSync(file)) {
return Object.assign({
from: file,
to: path.resolve(process.env.UNI_OUTPUT_DIR)
}, options)
}
}
const from = path.resolve(process.env.UNI_INPUT_DIR, file)
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, file)
}, options)
}
}
function getCopyOptions (files, options = {}, subPackages = true) {
const copyOptions = []
files.forEach(file => {
// 主包
const copyOption = getCopyOption(file, options)
if (copyOption) {
copyOptions.push(copyOption)
}
if (subPackages) {
// 分包
Object.keys(process.UNI_SUBPACKAGES).forEach(root => { // 分包静态资源
const subCopyOption = getCopyOption(path.join(root, file), options)
if (subCopyOption) {
copyOptions.push(subCopyOption)
}
})
}
})
return copyOptions
}
function getStaticCopyOptions (assetsDir) {
const ignore = []
Object.keys(PLATFORMS).forEach(platform => {
if (process.env.UNI_PLATFORM !== platform) {
ignore.push(platform + '/**/*')
}
})
return getCopyOptions(
[assetsDir], {
ignore
}
)
}
const PLATFORMS = {
'h5': {
global: '',
exts: false,
vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue',
compiler: false,
filterTag: 'wxs',
subPackages: false,
cssVars: {
'--status-bar-height': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
const indexCssCopyOptions = [{
from: require.resolve('@dcloudio/uni-h5/dist/index.css'),
to: assetsDir,
transform (content) {
if (process.env.NODE_ENV === 'production') {
return content + getShadowCss()
}
return content
}
}]
const VUE_APP_INDEX_CSS_HASH = process.env.VUE_APP_INDEX_CSS_HASH
if (VUE_APP_INDEX_CSS_HASH) {
const {
getH5Options
} = require('./manifest')
const {
template
} = getH5Options()
const to = path.join(assetsDir, `[name].${VUE_APP_INDEX_CSS_HASH}.[ext]`)
if (process.env.NODE_ENV === 'production') {
const templateContent = fs.readFileSync(template, {
encoding: 'utf8'
})
if (/\bVUE_APP_INDEX_CSS_HASH\b/.test(templateContent)) {
indexCssCopyOptions[0].to = to
}
} else {
const indexCssCopyOption = Object.assign({}, indexCssCopyOptions[0])
indexCssCopyOption.to = to
indexCssCopyOptions.push(indexCssCopyOption)
}
}
return [
...getStaticCopyOptions(assetsDir),
...indexCssCopyOptions,
...getCopyOptions(['hybrid/html'])
]
}
},
'app-plus': {
global: 'wx',
exts: {
style: '.wxss',
template: '.wxml',
filter: '.wxs'
},
filterTag: 'wxs',
subPackages: false,
cssVars: {},
copyWebpackOptions ({
assetsDir,
vueOptions
}) {
if (
vueOptions &&
vueOptions.pluginOptions &&
vueOptions.pluginOptions['uni-app-plus'] &&
vueOptions.pluginOptions['uni-app-plus']['view']
) { // app-view 无需拷贝资源(app-service 已经做了)
return []
}
const files = ['hybrid/html']
let wxcomponents = []
if (
!process.env.UNI_USING_NATIVE &&
!process.env.UNI_USING_V3 &&
!process.env.UNI_USING_V3_NATIVE
) {
wxcomponents = getCopyOptions(['wxcomponents'], {
to: path.resolve(process.env.UNI_OUTPUT_TMP_DIR, 'wxcomponents')
})
}
let template = []
let view = []
if (process.env.UNI_USING_V3) {
view = getCopyOptions([
require.resolve('@dcloudio/uni-app-plus/dist/view.css'),
require.resolve('@dcloudio/uni-app-plus/dist/view.umd.min.js')
])
template = [
...getCopyOptions([path.resolve(__dirname, '../template/common')]),
...getCopyOptions([path.resolve(__dirname, '../template/v3')])
]
}
return [
...view,
...template,
...getStaticCopyOptions(assetsDir),
...wxcomponents,
...getCopyOptions(files)
]
}
},
'mp-qq': {
global: 'wx',
exts: {
style: '.qss',
template: '.qml',
filter: '.wxs'
},
filterTag: 'wxs',
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.config.json',
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['wxcomponents'])
]
}
},
'mp-weixin': {
global: 'wx',
exts: {
style: '.wxss',
template: '.wxml',
filter: '.wxs'
},
filterTag: 'wxs',
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.config.json',
copyWebpackOptions ({
assetsDir,
manifestPlatformOptions
}) {
const files = [
'sitemap.json',
'ext.json',
'custom-tab-bar'
]
if (manifestPlatformOptions.workers) {
files.push(manifestPlatformOptions.workers)
}
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['wxcomponents']),
...getCopyOptions(files, {}, false)
]
}
},
'mp-baidu': {
global: 'swan',
exts: {
style: '.css',
template: '.swan',
filter: '.filter.js'
},
filterTag: 'filter',
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.swan.json',
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['swancomponents'])
]
}
},
'mp-alipay': {
global: 'my',
exts: {
style: '.acss',
template: '.axml',
filter: '.sjs'
},
filterTag: 'sjs',
subPackages: true,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['mycomponents'])
]
}
},
'mp-toutiao': {
global: 'tt',
exts: {
style: '.ttss',
template: '.ttml'
},
subPackages: false,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
project: 'project.tt.json',
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['ttcomponents'])
]
}
},
'quickapp': {
vue: '@dcloudio/vue-cli-plugin-uni/packages/h5-vue',
subPackages: false,
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
copyWebpackOptions ({
assetsDir
}) {
return [
...getStaticCopyOptions(assetsDir),
...getCopyOptions(['qacomponents'])
]
}
}
}
// 解决 vue-cli-service lint 时 UNI_PLATFORM 不存在
process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'
const platform = PLATFORMS[process.env.UNI_PLATFORM]
const preprocessContext = {}
Object.keys(PLATFORMS).forEach(platform => {
preprocessContext[platform.toUpperCase()] = false
})
preprocessContext[process.env.UNI_PLATFORM.toUpperCase()] = true
preprocessContext['MP'] = false
preprocessContext['APP'] = false
preprocessContext['APP-PLUS-NVUE'] = false
preprocessContext['APP_PLUS_NVUE'] = false
preprocessContext['APP-VUE'] = false
preprocessContext['APP_VUE'] = false
preprocessContext['APP-NVUE'] = false
preprocessContext['APP_NVUE'] = false
if (process.env.UNI_PLATFORM === 'app-plus') {
preprocessContext['APP-VUE'] = true
preprocessContext['APP_VUE'] = true
}
if (process.env.UNI_PLATFORM.indexOf('mp-') === 0) {
preprocessContext['MP'] = true
}
if (process.env.UNI_PLATFORM.indexOf('app-') === 0) {
preprocessContext['APP'] = true
}
if (process.UNI_SCRIPT_DEFINE && Object.keys(process.UNI_SCRIPT_DEFINE).length) {
Object.keys(process.UNI_SCRIPT_DEFINE).forEach(name => {
preprocessContext[name] = process.UNI_SCRIPT_DEFINE[name]
})
}
Object.keys(preprocessContext).forEach(platform => {
if (platform.indexOf('-') !== -1) {
preprocessContext[platform.replace(/-/g, '_')] = preprocessContext[platform]
}
})
const nvuePreprocessContext = Object.assign({}, preprocessContext, {
'APP-VUE': false,
'APP_VUE': false,
'APP-NVUE': true,
'APP_NVUE': true,
'APP-PLUS-NVUE': true,
'APP_PLUS_NVUE': true
})
const isInHBuilderX = fs.existsSync(path.resolve(process.env.UNI_CLI_CONTEXT, 'bin/uniapp-cli.js'))
let isInHBuilderXAlpha = false
if (isInHBuilderX) {
try {
if (require(path.resolve(process.env.UNI_CLI_CONTEXT, '../about/package.json')).alpha) {
isInHBuilderXAlpha = true
}
} catch (e) {
}
}
let sourceRoot = false
function devtoolModuleFilenameTemplate (info) {
if (!sourceRoot) {
if (isInHBuilderX) {
sourceRoot = normalizePath(process.env.UNI_INPUT_DIR)
} else {
sourceRoot = normalizePath(process.env.UNI_CLI_CONTEXT)
}
}
let filePath = false
const absoluteResourcePath = normalizePath(info.absoluteResourcePath)
if (
absoluteResourcePath.indexOf(sourceRoot) !== -1 &&
(
absoluteResourcePath.endsWith('.js') ||
absoluteResourcePath.endsWith('.ts')
)
) {
filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
if (
filePath.indexOf('node_modules/@dcloudio') === 0 ||
filePath.indexOf('node_modules/vue-loader') === 0 ||
filePath.indexOf('node_modules/webpack') === 0
) {
filePath = false
}
} else if (
!info.moduleId &&
(
absoluteResourcePath.endsWith('.vue') ||
absoluteResourcePath.endsWith('.nvue')
)
) {
if (
absoluteResourcePath.indexOf('src') !== 0 &&
absoluteResourcePath.indexOf('node-modules') !== 0
) {
filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
} else {
filePath = absoluteResourcePath
}
}
if (
filePath &&
filePath !== 'main.js' &&
filePath !== 'main.ts' &&
filePath !== 'src/main.js' &&
filePath !== 'src/main.ts'
) {
return `uni-app:///${filePath}`
}
}
const NODE_MODULES_REGEX = /(\.\.\/)?node_modules/g
function normalizeNodeModules (str) {
str = str.replace(NODE_MODULES_REGEX, 'node-modules')
if (process.env.UNI_PLATFORM === 'mp-alipay') {
str = str.replace('node-modules/@', 'node-modules/npm-scope-')
}
return str
}
const uniPluginOptions = global.uniPlugin.options || {}
const {
vueContext: preprocessContext,
nvueContext: nvuePreprocessContext
} = global.uniPlugin.preprocess
// TODO 暂时保留原有导出,减少影响,后续再整理一下
module.exports = {
normalizeNodeModules,
isInHBuilderX,
isInHBuilderXAlpha,
runByHBuilderX: isInHBuilderX || fs.existsSync(path.resolve(process.env.UNI_HBUILDERX_PLUGINS || '', 'weapp-tools')),
devtoolModuleFilenameTemplate,
getFlexDirection (json) {
let flexDir = 'column'
if (json && json['nvue'] && json['nvue']['flex-direction']) {
......@@ -512,40 +71,28 @@ module.exports = {
context: nvuePreprocessContext
},
isSupportSubPackages () {
return platform.subPackages
return !!uniPluginOptions.subPackages
},
getPlatforms () {
return Object.keys(PLATFORMS)
},
getPlatformCopy () {
return platform.copyWebpackOptions
},
getPlatformGlobal () {
return platform.global
return global.uniPlugin.platforms
},
getPlatformExts () {
return platform.exts
getPlatformGlobal () { // 目前仅mp-alipay有用
return uniPluginOptions.global
},
getPlatformTarget () {
return platform.megalo
getPlatformExts () { // 小程序扩展名
return uniPluginOptions.extnames
},
getPlatformProject () {
return platform.project
getPlatformProject () { // 开发工具项目配置名
return uniPluginOptions.project
},
getPlatformFilterTag () {
return platform.filterTag
return uniPluginOptions.filterTag
},
getPlatformVue (vueOptions) {
if (process.env.UNI_PLATFORM === 'h5' && vueOptions && vueOptions.runtimeCompiler) {
return '@dcloudio/vue-cli-plugin-uni/packages/h5-vue/dist/vue.esm.js'
}
if (process.env.UNI_USING_COMPONENTS) {
return uniRuntime
}
return platform.vue
return uniPluginOptions.vue || '@dcloudio/vue-cli-plugin-uni/packages/mp-vue'
},
getPlatformCssVars () {
return platform.cssVars
return uniPluginOptions.cssVars
},
getPlatformCssnano () {
return {
......
const path = require('path')
const initPreprocessContext = require('./preprocess')
const Plugin = {
options: {},
// 初步校验相关配置是否正确
validate: [], // (platformOptions, manifestJson) {},
// 以 H5 为基准的平台特殊配置
configureH5: [], // (h5Options) {},
// 链式修改 webpack config
chainWebpack: [], // (config, vueOptions, api) {},
// 修改 webpack config
configureWebpack: [], // (config, vueOptions, api) {},
// 配置额外的资源拷贝
copyWebpackOptions: [] // (platformOptions, vueOptions) {}
}
const PLUGIN_KEYS = Object.keys(Plugin)
function initPlugin (plugin) {
let pluginApi
try {
pluginApi = require(path.join(plugin.id, (plugin.config.main || '/lib/uni.config.js')))
} catch (e) {
console.warn(`缺少 uni.config.js `)
}
pluginApi && PLUGIN_KEYS.forEach(name => {
if (pluginApi[name]) {
if (Array.isArray(Plugin[name])) { // hooks
Plugin[name].push(pluginApi[name])
} else { // options
Object.assign(Plugin[name], pluginApi[name])
}
}
})
}
const pluginRE = /^(uni-|@[\w-]+(\.)?[\w-]+\/uni-)/
const officialPlugins = [
'@dcloudio/uni-app-plus',
'@dcloudio/uni-h5',
'@dcloudio/uni-mp-alipay',
'@dcloudio/uni-mp-baidu',
'@dcloudio/uni-mp-qq',
'@dcloudio/uni-mp-toutiao',
'@dcloudio/uni-mp-welink',
'@dcloudio/uni-mp-weixin'
]
function resolvePlugins () {
const pkg = require(path.resolve(process.env.UNI_CLI_CONTEXT, 'package.json'))
return Object.keys(pkg.devDependencies || {})
.concat(Object.keys(pkg.dependencies || {}))
.map(id => {
let isPlatformPlugin = false
if (id.startsWith('@dcloudio/')) {
if (!officialPlugins.includes(id)) {
return
}
isPlatformPlugin = true
} else {
isPlatformPlugin = pluginRE.test(id)
}
if (!isPlatformPlugin) {
return
}
try {
const pluginPkg = require(id + '/package.json')
const config = pluginPkg['uni-app']
if (!config) {
return
}
if (!config.name) {
return console.warn(`${id}/package.json->uni-app 缺少 name 属性`)
}
return {
id,
name: config.name,
config
}
} catch (e) {}
}).filter(Boolean)
}
function initExtends (name, plugin, plugins) {
const extendsPlatform = plugin.config['extends']
if (extendsPlatform) {
if (extendsPlatform !== 'h5') {
console.error(`目前仅支持基于 h5 平台做扩展`)
process.exit(0)
}
const extendsPlugin = plugins.find(plugin => plugin.name === extendsPlatform)
if (!plugin) {
console.error(`缺少平台 ${extendsPlatform} 插件`)
process.exit(0)
}
process.env.UNI_SUB_PLATFORM = name
process.env.UNI_PLATFORM = extendsPlatform
initPlugin(extendsPlugin)
}
}
module.exports = {
init () {
const plugins = resolvePlugins()
const plugin = plugins.find(plugin => plugin.name === process.env.UNI_PLATFORM)
if (!plugin) {
console.error(`缺少平台 ${process.env.UNI_PLATFORM} 插件`)
process.exit(0)
}
const name = plugin.name
initExtends(name, plugin, plugins)
initPlugin(plugin)
Plugin.name = name
Plugin.config = plugin.config
Plugin.platforms = plugins.map(plugin => plugin.name)
Plugin.preprocess = initPreprocessContext(name, Plugin.platforms, process.UNI_SCRIPT_DEFINE)
return Plugin
}
}
const DEFAULT_KEYS = [
'MP',
'APP',
'APP-PLUS-NVUE',
'APP-VUE',
'APP-NVUE'
]
function normalize (name) {
return name.replace(/-/g, '_').toUpperCase()
}
module.exports = function initPreprocess (name, platforms, userDefines = {}) {
const vueContext = {} // vue 值为true的条件编译
const nvueContext = {} // nvue 值为true的条件编译
const defaultContext = {}
const userDefineKeys = Object.keys(userDefines)
platforms
.concat(DEFAULT_KEYS)
.concat(userDefineKeys)
.forEach(name => {
defaultContext[normalize(name)] = false
})
vueContext[normalize(name)] = true
if (name === 'app-plus') {
vueContext['APP_VUE'] = true
nvueContext['APP_PLUS'] = true
nvueContext['APP_NVUE'] = true
nvueContext['APP_PLUS_NVUE'] = true
}
if (name.startsWith('mp-')) {
vueContext['MP'] = true
}
if (name.startsWith('app-')) {
vueContext['APP'] = true
}
userDefineKeys.forEach(name => {
if (userDefines[name]) {
const key = normalize(name)
vueContext[key] = nvueContext[key] = true
}
})
return {
vueContext: {
...defaultContext,
...vueContext
},
nvueContext: {
...defaultContext,
...nvueContext
}
}
}
......@@ -2,21 +2,18 @@ const path = require('path')
const hash = require('hash-sum')
const crypto = require('crypto')
const PLATFORMS = [
'h5',
'app-plus',
'mp-qq',
'mp-weixin',
'mp-baidu',
'mp-alipay',
'mp-toutiao',
'quickapp'
]
const isWin = /^win/.test(process.platform)
const normalizePath = path => (isWin ? path.replace(/\\/g, '/') : path)
let aboutPkg
try {
aboutPkg = require(path.resolve(__dirname, '../../../../../about/package.json'))
} catch (e) {}
const isInHBuilderX = !!aboutPkg
const isInHBuilderXAlpha = !!(isInHBuilderX && aboutPkg.alpha)
function removeExt (str, ext) {
if (ext) {
const reg = new RegExp(ext.replace(/\./, '\\.') + '$')
......@@ -48,11 +45,11 @@ const camelizeRE = /-(\w)/g
const camelize = cached((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
})
})
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
}
const hyphenateRE = /\B([A-Z])/g
......@@ -91,7 +88,20 @@ function hasModule (name) {
return false
}
const NODE_MODULES_REGEX = /(\.\.\/)?node_modules/g
function normalizeNodeModules (str) {
str = str.replace(NODE_MODULES_REGEX, 'node-modules')
if (process.env.UNI_PLATFORM === 'mp-alipay') {
str = str.replace('node-modules/@', 'node-modules/npm-scope-')
}
return str
}
module.exports = {
isInHBuilderX,
isInHBuilderXAlpha,
normalizeNodeModules,
md5,
hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
......@@ -99,7 +109,7 @@ module.exports = {
hasModule,
parseStyle (style = {}) {
Object.keys(style).forEach(name => {
if (PLATFORMS.includes(name)) {
if (global.uniPlugin.platforms.includes(name)) {
if (name === process.env.UNI_PLATFORM) {
Object.assign(style, style[name] || {})
}
......@@ -110,7 +120,7 @@ module.exports = {
},
hashify,
removeExt,
camelize,
camelize,
capitalize,
hyphenate,
normalizePath,
......@@ -124,4 +134,4 @@ module.exports = {
getTemplatePath () {
return path.join(__dirname, '../template')
}
}
}
{
"name": "@dcloudio/uni-h5",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app h5",
"main": "dist/index.umd.min.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-h5"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"dependencies": {
"base64-arraybuffer": "^0.2.0",
"intersection-observer": "^0.7.0",
"safe-area-insets": "^1.4.1"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-h5",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app h5",
"main": "dist/index.umd.min.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-h5"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"dependencies": {
"base64-arraybuffer": "^0.2.0",
"intersection-observer": "^0.7.0",
"safe-area-insets": "^1.4.1"
},
"uni-app": {
"name": "h5",
"title": "H5",
"main": "lib/h5/uni.config.js"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
......@@ -9,7 +9,7 @@ const migraters = {
'mp-weixin': require('./mp-weixin')
}
module.exports = function migrate(input, out, options = {}) {
module.exports = function migrate (input, out, options = {}) {
options.platform = options.platform || 'mp-weixin'
const migrater = migraters[options.platform]
if (!migrater) {
......@@ -42,7 +42,7 @@ module.exports = function migrate(input, out, options = {}) {
try {
fs.copySync(src, dest)
} catch (e) {
//ignore Source and destination must not be the same
// ignore Source and destination must not be the same
}
}
} else {
......
......@@ -4,14 +4,14 @@ const normalizePath = path => (isWin ? path.replace(/\\/g, '/') : path)
const camelizeRE = /-(\w)/g
function camelize(str) {
function camelize (str) {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
}
/**
* Capitalize a string.
*/
function capitalize(str) {
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
......
......@@ -5,7 +5,7 @@ const migraters = {
'mp-weixin': require('./mp-weixin')
}
module.exports = function validate(input, out, options) {
module.exports = function validate (input, out, options) {
if (!fs.existsSync(input)) {
return console.error(`错误: '${input}' 不存在`)
}
......
......@@ -5,7 +5,7 @@ const {
normalizePath
} = require('./util')
module.exports = function patchVant(files, assets, out) {
module.exports = function patchVant (files, assets, out) {
files.forEach(file => {
const filepath = normalizePath(file.path)
let changed = false
......
module.exports = {
options: {
global: 'my',
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
extnames: {
style: '.acss',
template: '.axml',
filter: '.sjs'
},
filterTag: 'sjs',
subPackages: true
},
copyWebpackOptions (platformOptions, vueOptions) {
return ['mycomponents']
}
}
{
"name": "@dcloudio/uni-mp-alipay",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-alipay",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-alipay"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-mp-alipay",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-alipay",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-alipay"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"uni-app": {
"name": "mp-alipay",
"title": "支付宝小程序"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
module.exports = {
options: {
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
extnames: {
style: '.css',
template: '.swan',
filter: '.filter.js'
},
filterTag: 'filter',
project: 'project.swan.json',
subPackages: true
},
copyWebpackOptions (platformOptions, vueOptions) {
return ['swancomponents']
}
}
{
"name": "@dcloudio/uni-mp-baidu",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-baidu",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-baidu"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-mp-baidu",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-baidu",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-baidu"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"uni-app": {
"name": "mp-baidu",
"title": "百度小程序"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
const fs = require('fs')
const path = require('path')
const COMPONENTS_DIR_NAME = 'wxcomponents'
module.exports = {
options: {
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
extnames: {
style: '.qss',
template: '.qml',
filter: '.wxs'
},
filterTag: 'wxs',
project: 'project.config.json',
subPackages: true
},
copyWebpackOptions (platformOptions, vueOptions) {
const copyOptions = [
// 'sitemap.json',
// 'ext.json',
'custom-tab-bar'
]
const workers = platformOptions.workers
workers && copyOptions.push(workers)
const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME)
if (fs.existsSync(wxcomponentsDir)) {
copyOptions.push({
from: wxcomponentsDir,
to: COMPONENTS_DIR_NAME,
ignore: ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤
})
}
return copyOptions
}
}
{
"name": "@dcloudio/uni-mp-qq",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-qq",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-qq"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-mp-qq",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-qq",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-qq"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"uni-app": {
"name": "mp-qq",
"title": "QQ小程序"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
module.exports = {
options: {
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
extnames: {
style: '.ttss',
template: '.ttml'
},
project: 'project.tt.json'
},
copyWebpackOptions (platformOptions, vueOptions) {
return ['ttcomponents']
}
}
{
"name": "@dcloudio/uni-mp-toutiao",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-toutiao",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-toutiao"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-mp-toutiao",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-toutiao",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-toutiao"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"uni-app": {
"name": "mp-toutiao",
"title": "字节跳动小程序"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
const fs = require('fs')
const path = require('path')
const COMPONENTS_DIR_NAME = 'wxcomponents'
module.exports = {
options: {
cssVars: {
'--status-bar-height': '25px',
'--window-top': '0px',
'--window-bottom': '0px'
},
extnames: {
style: '.wxss',
template: '.wxml',
filter: '.wxs'
},
filterTag: 'wxs',
project: 'project.config.json',
subPackages: true
},
copyWebpackOptions (platformOptions, vueOptions) {
const copyOptions = [
'sitemap.json',
'ext.json',
'custom-tab-bar'
]
const workers = platformOptions.workers
workers && copyOptions.push(workers)
const wxcomponentsDir = path.resolve(process.env.UNI_INPUT_DIR, COMPONENTS_DIR_NAME)
if (fs.existsSync(wxcomponentsDir)) {
copyOptions.push({
from: wxcomponentsDir,
to: COMPONENTS_DIR_NAME,
ignore: ['**/*.vue', '**/*.css'] // v3 会自动转换生成vue,css文件,需要过滤
})
}
return copyOptions
}
}
{
"name": "@dcloudio/uni-mp-weixin",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-weixin",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-weixin"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
{
"name": "@dcloudio/uni-mp-weixin",
"version": "2.0.0-alpha-26420200309002",
"description": "uni-app mp-weixin",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-weixin"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fxy060608",
"license": "Apache-2.0",
"uni-app": {
"name": "mp-weixin",
"title": "微信小程序"
},
"gitHead": "84e9cb1ca1898054d161f1514efadd1ab24fd804"
}
const vueLoader = require('@dcloudio/uni-cli-shared/lib/vue-loader')
module.exports = config => {
module.exports = config => {
config.module
.rule('vue')
.test(vueLoader.test)
.use('vue-loader')
.loader(vueLoader.loader)
.tap(options => Object.assign(options, vueLoader.options({}, {
quickapp: true,
quickapp: true
})))
config.module
......
module.exports = {
preTransformNode(el) {
preTransformNode (el) {
if (el.tag === 'view') { // view 是最常用组件,直接映射为div标签,保证性能
el.tag = 'div'
}
......
......@@ -27,37 +27,35 @@ const env = {
const dslFilename = ('vue.' + (process.env.NODE_ENV === 'production' ? 'prod' : 'dev') + '.js')
const manifest = global.framework.manifest
function genPriorities(entryPagePath) {
const o = [/^i18n\/.+\.json$/i, 'manifest.json', 'app.js', /^common\//i];
function genPriorities (entryPagePath) {
const o = [/^i18n\/.+\.json$/i, 'manifest.json', 'app.js', /^common\//i]
if (entryPagePath) {
o.splice(3, 0, new RegExp(`^${entryPagePath}/$`), new RegExp(`^${entryPagePath}/.+`))
} else console.error('未配置入口页面');
} else console.error('未配置入口页面')
return o
}
module.exports = {
devtool: false,
entry() {
entry () {
return process.UNI_ENTRY
},
output: {
filename: '[name].js',
chunkFilename: '[name].js'
filename: '[name].js',
chunkFilename: '[name].js'
},
optimization: {
splitChunks: false,
runtimeChunk: false
splitChunks: false,
runtimeChunk: false
},
externals: {
vue: 'Vue'
},
module: {
rules: [{
//暂不考虑ts
// 暂不考虑ts
test: path.resolve(process.env.UNI_INPUT_DIR, 'main.js'),
use: [{
loader: path.resolve(__dirname, 'loader/main-loader')
......
const fs = require('fs')
const path = require('path')
module.exports = function() {
module.exports = function () {
const manifest = global.framework.manifest
if (manifest.package === 'Bundle') {
......
......@@ -8,9 +8,9 @@
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-quickapp"
},
"files": [
"bin",
"components",
"files": [
"bin",
"components",
"dist",
"lib"
],
......@@ -20,6 +20,10 @@
"author": "fxy060608",
"license": "Apache-2.0",
"gitHead": "110501ffb0313e417858dec92acf07522d4ded00",
"uni-app": {
"name": "quickapp",
"title": "快应用"
},
"dependencies": {
"@hap-toolkit/dsl-vue": "0.6.13",
"@hap-toolkit/packager": "0.6.13",
......
......@@ -8,10 +8,13 @@ const {
getNVueMainEntry,
nvueJsPreprocessOptions,
nvueHtmlPreprocessOptions,
devtoolModuleFilenameTemplate,
getTemplatePath
} = require('@dcloudio/uni-cli-shared')
const {
devtoolModuleFilenameTemplate
} = require('../util')
const WebpackAppPlusNVuePlugin = process.env.UNI_USING_V3
? require('../packages/webpack-app-plus-plugin')
: require('../packages/webpack-app-plus-nvue-plugin')
......
......@@ -7,10 +7,6 @@ process.env.UNI_HBUILDERX_PLUGINS = process.env.UNI_HBUILDERX_PLUGINS || path.re
require('./module-alias')
const {
devtoolModuleFilenameTemplate
} = require('@dcloudio/uni-cli-shared')
module.exports = (api, options) => { // 仅处理 app-plus 相关逻辑
if (process.env.UNI_PLATFORM !== 'app-plus') {
return
......@@ -40,6 +36,10 @@ module.exports = (api, options) => { // 仅处理 app-plus 相关逻辑
plugins.push(new WebpackAppPlusPlugin())
const {
devtoolModuleFilenameTemplate
} = require('./util')
// sourcemap 输出相对路径
output.devtoolModuleFilenameTemplate = devtoolModuleFilenameTemplate
......
const fs = require('fs')
const path = require('path')
const moduleAlias = require('module-alias')
const {
hasModule,
isInHBuilderX
} = require('@dcloudio/uni-cli-shared')
hasModule
} = require('@dcloudio/uni-cli-shared/lib/util')
const isInHBuilderX = fs.existsSync(path.resolve(process.env.UNI_CLI_CONTEXT, 'bin/uniapp-cli.js'))
// nvue override
moduleAlias.addAlias('weex-styler', path.resolve(__dirname, 'packages/weex-styler'))
moduleAlias.addAlias('weex-template-compiler', path.resolve(__dirname, 'packages/weex-template-compiler'))
moduleAlias.addAlias('@vue/component-compiler-utils', require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils'))
moduleAlias.addAlias('@vue/component-compiler-utils/package.json', require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils/package.json'))
moduleAlias.addAlias('@vue/component-compiler-utils', require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils'))
moduleAlias.addAlias('@vue/component-compiler-utils/package.json', require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils/package.json'))
if (isInHBuilderX) {
moduleAlias.addAlias('typescript', path.resolve(process.env.UNI_HBUILDERX_PLUGINS,
......
const path = require('path')
const {
normalizePath,
isInHBuilderX
} = require('@dcloudio/uni-cli-shared/lib/util')
let sourceRoot = false
function devtoolModuleFilenameTemplate (info) {
if (!sourceRoot) {
if (isInHBuilderX) {
sourceRoot = normalizePath(process.env.UNI_INPUT_DIR)
} else {
sourceRoot = normalizePath(process.env.UNI_CLI_CONTEXT)
}
}
let filePath = false
const absoluteResourcePath = normalizePath(info.absoluteResourcePath)
if (
absoluteResourcePath.indexOf(sourceRoot) !== -1 &&
(
absoluteResourcePath.endsWith('.js') ||
absoluteResourcePath.endsWith('.ts')
)
) {
filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
if (
filePath.indexOf('node_modules/@dcloudio') === 0 ||
filePath.indexOf('node_modules/vue-loader') === 0 ||
filePath.indexOf('node_modules/webpack') === 0
) {
filePath = false
}
} else if (
!info.moduleId &&
(
absoluteResourcePath.endsWith('.vue') ||
absoluteResourcePath.endsWith('.nvue')
)
) {
if (
absoluteResourcePath.indexOf('src') !== 0 &&
absoluteResourcePath.indexOf('node-modules') !== 0
) {
filePath = normalizePath(path.relative(sourceRoot, absoluteResourcePath))
} else {
filePath = absoluteResourcePath
}
}
if (
filePath &&
filePath !== 'main.js' &&
filePath !== 'main.ts' &&
filePath !== 'src/main.js' &&
filePath !== 'src/main.ts'
) {
return `uni-app:///${filePath}`
}
}
module.exports = {
devtoolModuleFilenameTemplate
}
......@@ -22,7 +22,7 @@ module.exports = (api, options) => {
if (process.env.UNI_PLATFORM === 'quickapp') {
process.env.UNI_OUTPUT_DIR = path.resolve(process.env.UNI_OUTPUT_DIR, 'build')
Object.assign(options, {
assetsDir,
assetsDir,
parallel: false,
outputDir: process.env.UNI_OUTPUT_DIR
})
......@@ -59,6 +59,13 @@ module.exports = (api, options) => {
api.configureWebpack(require('./lib/configure-webpack')(platformOptions, manifestPlatformOptions, options, api))
api.chainWebpack(require('./lib/chain-webpack')(platformOptions, options, api))
global.uniPlugin.configureWebpack.forEach(configureWebpack => {
api.configureWebpack(configureWebpack)
})
global.uniPlugin.chainWebpack.forEach(chainWebpack => {
api.chainWebpack(chainWebpack)
})
if (
process.env.UNI_PLATFORM === 'h5' ||
(
......
......@@ -23,11 +23,14 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
runByHBuilderX, // 使用 HBuilderX 运行
isInHBuilderX, // 在 HBuilderX 的插件中
hasModule,
getPlatformVue,
jsPreprocessOptions,
htmlPreprocessOptions
} = require('@dcloudio/uni-cli-shared')
const {
getPlatformVue
} = require('@dcloudio/uni-cli-shared/lib/platform')
const {
getCopyWebpackPluginOptions
} = require('./copy-webpack-options')
......@@ -184,9 +187,16 @@ module.exports = function configureWebpack (platformOptions, manifestPlatformOpt
webpackConfig.resolve.modules = webpackConfig.resolve.modules.filter(module => module !==
'node_modules')
const plugins = [
new CopyWebpackPlugin(getCopyWebpackPluginOptions(manifestPlatformOptions))
]
const plugins = []
const isAppView = process.env.UNI_PLATFORM === 'app-plus' &&
vueOptions.pluginOptions &&
vueOptions.pluginOptions['uni-app-plus'] &&
vueOptions.pluginOptions['uni-app-plus']['view']
if (!isAppView) { // app-plus view不需要copy
plugins.push(new CopyWebpackPlugin(getCopyWebpackPluginOptions(manifestPlatformOptions, vueOptions)))
}
if (process.UNI_SCRIPT_ENV && Object.keys(process.UNI_SCRIPT_ENV).length) {
// custom define
......
const fs = require('fs')
const path = require('path')
const assetsDir = 'static'
function getCopyWebpackPluginOptions (manifestPlatformOptions, vueOptions) {
const {
getPlatformCopy
} = require('@dcloudio/uni-cli-shared/lib/platform')
function getAssetsCopyOption (from, options = {}) {
if (path.isAbsolute(from)) {
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR)
}, options)
}
}
const to = from
from = path.resolve(process.env.UNI_INPUT_DIR, from)
if (fs.existsSync(from)) {
return Object.assign({
from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, to)
}, options)
}
}
// 暂未考虑动态添加static目录
function getAssetsCopyOptions (assetsDir) {
const ignore = []
global.uniPlugin.platforms.forEach(platform => {
if (global.uniPlugin.name !== platform) {
ignore.push(platform + '/**/*')
}
})
const copyOptions = []
// 主包静态资源
const mainAssetsCopyOption = getAssetsCopyOption(assetsDir, {
ignore
})
if (mainAssetsCopyOption) {
copyOptions.push(mainAssetsCopyOption)
}
// 分包静态资源
process.UNI_SUBPACKAGES && Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
const subAssetsCopyOption = getAssetsCopyOption(path.join(root, assetsDir), {
ignore
})
if (subAssetsCopyOption) {
copyOptions.push(subAssetsCopyOption)
}
})
return copyOptions
}
return getPlatformCopy()({
assetsDir,
manifestPlatformOptions,
vueOptions
function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
const copyOptions = getAssetsCopyOptions(assetsDir)
global.uniPlugin.copyWebpackOptions.forEach(copyWebpackOptions => {
const platformCopyOptions = copyWebpackOptions(platformOptions, vueOptions) || []
platformCopyOptions.forEach(copyOption => {
if (typeof copyOption === 'string') {
copyOption = getAssetsCopyOption(copyOption)
}
copyOption && copyOptions.push(copyOption)
})
})
console.log('debug:::', copyOptions)
return copyOptions
}
module.exports = {
......
......@@ -3,6 +3,24 @@ const path = require('path')
const mkdirp = require('mkdirp')
const loaderUtils = require('loader-utils')
const defaultInputDir = 'src'
if (process.env.UNI_INPUT_DIR && process.env.UNI_INPUT_DIR.indexOf('./') === 0) {
process.env.UNI_INPUT_DIR = path.resolve(process.cwd(), process.env.UNI_INPUT_DIR)
}
process.env.UNI_INPUT_DIR = process.env.UNI_INPUT_DIR || path.resolve(process.cwd(), defaultInputDir)
// 初始化全局插件对象
global.uniPlugin = require('@dcloudio/uni-cli-shared/lib/plugin').init()
console.log('debug:::', global.uniPlugin)
const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson()
const platformOptions = manifestJsonObj[process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM] || {}
// 插件校验环境
global.uniPlugin.validate.forEach(validate => {
validate(platformOptions, manifestJsonObj)
})
process.UNI_MANIFEST = manifestJsonObj
process.UNI_CLOUD = false
process.UNI_CLOUD_TCB = false
process.UNI_CLOUD_ALIYUN = false
......@@ -49,21 +67,16 @@ if (
}
// 初始化环境变量
const defaultInputDir = '../../../../src'
const defaultOutputDir = '../../../../dist/' +
(process.env.NODE_ENV === 'production' ? 'build' : 'dev') + '/' +
process.env.UNI_PLATFORM
(process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM)
if (process.env.UNI_INPUT_DIR && process.env.UNI_INPUT_DIR.indexOf('./') === 0) {
process.env.UNI_INPUT_DIR = path.resolve(process.cwd(), process.env.UNI_INPUT_DIR)
}
if (process.env.UNI_OUTPUT_DIR && process.env.UNI_OUTPUT_DIR.indexOf('./') === 0) {
process.env.UNI_OUTPUT_DIR = path.resolve(process.cwd(), process.env.UNI_OUTPUT_DIR)
}
process.env.UNI_PLATFORM = process.env.UNI_PLATFORM || 'h5'
process.env.VUE_APP_PLATFORM = process.env.UNI_PLATFORM
process.env.UNI_INPUT_DIR = process.env.UNI_INPUT_DIR || path.resolve(__dirname, defaultInputDir)
process.env.UNI_OUTPUT_DIR = process.env.UNI_OUTPUT_DIR || path.resolve(__dirname, defaultOutputDir)
if (process.env.UNI_PLATFORM === 'app-plus') {
......@@ -82,9 +95,7 @@ const {
normalizePath,
isSupportSubPackages,
runByHBuilderX,
// isInHBuilderXAlpha,
getPagesJson,
getManifestJson
getPagesJson
} = require('@dcloudio/uni-cli-shared')
const pagesJsonObj = getPagesJson()
......@@ -107,11 +118,7 @@ if (Array.isArray(pagesJsonObj.subPackages)) {
})
}
const manifestJsonObj = getManifestJson()
const platformOptions = manifestJsonObj[process.env.UNI_PLATFORM] || {}
process.UNI_PAGES = pagesJsonObj
process.UNI_MANIFEST = manifestJsonObj
if (manifestJsonObj.debug) {
process.env.VUE_APP_DEBUG = true
......@@ -178,7 +185,7 @@ if (process.env.UNI_PLATFORM === 'app-plus') {
) {
delete process.env.UNI_USING_CACHE
if (platformOptions.renderer === 'native') {
process.env.UNI_USING_V3_NATIVE = true
process.env.UNI_USING_V3_NATIVE = true
} else {
process.env.UNI_USING_V3 = true
platformOptions.usingComponents = true
......@@ -269,7 +276,8 @@ const needWarning = !platformOptions.usingComponents || usingComponentsAbsent
let hasNVue = false
// 输出编译器版本等信息
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
console.log('当前nvue编译模式' + (process.env.UNI_USING_V3_NATIVE ? '(v3)' : '') + '' + (isNVueCompiler ? 'uni-app' : 'weex') +
console.log('当前nvue编译模式' + (process.env.UNI_USING_V3_NATIVE ? '(v3)' : '') + '' + (isNVueCompiler ? 'uni-app'
: 'weex') +
' 。编译模式差异见:https://ask.dcloud.net.cn/article/36074')
} else if (process.env.UNI_PLATFORM !== 'h5' && process.env.UNI_PLATFORM !== 'quickapp') {
try {
......
const path = require('path')
const loaderUtils = require('loader-utils')
const {
removeExt,
getPlatformExts,
getShadowTemplate
} = require('@dcloudio/uni-cli-shared')
const {
getJsonFile,
getWXComponents,
updateSpecialMethods,
getGlobalUsingComponents,
updateGenericComponents, // resolve
updateComponentGenerics, // define
updateUsingGlobalComponents
} = require('@dcloudio/uni-cli-shared/lib/cache')
const {
getPlatformFilterTag
} = require('@dcloudio/uni-cli-shared/lib/platform')
const {
normalizeNodeModules
} = require('./shared')
const templateExt = getPlatformExts().template
const filterTagName = getPlatformFilterTag() || ''
function parseFilterModules (filterModules) {
if (filterModules) {
return JSON.parse(Buffer.from(filterModules, 'base64').toString('ascii'))
}
return {}
}
module.exports = function (content) {
this.cacheable && this.cacheable()
const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options')
if (vueLoaderOptions) {
const globalUsingComponents = getGlobalUsingComponents()
const realResourcePath = path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)
const resourcePath = normalizeNodeModules(removeExt(realResourcePath) + templateExt)
const wxComponents = getWXComponents(resourcePath.replace(path.extname(resourcePath), ''))
const params = loaderUtils.parseQuery(this.resourceQuery)
/* eslint-disable no-mixed-operators */
const filterModules = parseFilterModules(params && params['filter-modules'])
Object.assign(vueLoaderOptions.options.compilerOptions, {
mp: {
platform: process.env.UNI_PLATFORM
},
filterModules,
filterTagName,
resourcePath,
emitFile: this.emitFile,
wxComponents,
getJsonFile,
getShadowTemplate,
updateSpecialMethods,
globalUsingComponents,
updateGenericComponents,
updateComponentGenerics,
updateUsingGlobalComponents
})
} else {
throw new Error('vue-loader-options parse error')
}
return content
}
const path = require('path')
const qs = require('querystring')
const {
md5,
removeExt,
getPlatformExts
} = require('@dcloudio/uni-cli-shared')
const {
cacheTemplate,
cacheCompilerOptions,
getPlatformTarget
} = require('./shared')
const templateExt = getPlatformExts().template
module.exports = function (content) {
if (process.env.UNI_USING_COMPONENTS) {
return require('./template-new').call(this, content)
}
this.cacheable && this.cacheable()
const realResourcePath = path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)
if (process.env.UNI_USING_COMPONENTS) {
// 向 uni-template-compier 传递 emitFile
const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options')
if (vueLoaderOptions) {
Object.assign(vueLoaderOptions.options.compilerOptions, {
resourcePath: removeExt(realResourcePath) + templateExt,
emitFile: this.emitFile
})
} else {
throw new Error('vue-loader-options parse error')
}
} else {
if (!content.trim()) {
content = '<view></view>'
}
cacheTemplate(realResourcePath, content)
const query = qs.parse(this.resourceQuery.slice(1))
const {
id
} = query
const compilerOptions = {
scopeId: query.scoped ? `data-v-${id}` : null,
target: getPlatformTarget(),
md5: md5(content.trim() + process.env.UNI_PLATFORM),
realResourcePath
}
cacheCompilerOptions(realResourcePath, compilerOptions)
// 向 vue-loader templateLoader 传递 compilerOptions
const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options')
if (vueLoaderOptions) {
Object.assign(vueLoaderOptions.options.compilerOptions, compilerOptions)
} else {
throw new Error('vue-loader-options parse error')
}
}
return content
}
const path = require('path')
const qs = require('querystring')
const loaderUtils = require('loader-utils')
const {
md5,
removeExt,
getPlatformExts
getPlatformExts,
getShadowTemplate
} = require('@dcloudio/uni-cli-shared')
const {
cacheTemplate,
cacheCompilerOptions,
getPlatformTarget
getJsonFile,
getWXComponents,
updateSpecialMethods,
getGlobalUsingComponents,
updateGenericComponents, // resolve
updateComponentGenerics, // define
updateUsingGlobalComponents
} = require('@dcloudio/uni-cli-shared/lib/cache')
const {
getPlatformFilterTag
} = require('@dcloudio/uni-cli-shared/lib/platform')
const {
normalizeNodeModules
} = require('./shared')
const templateExt = getPlatformExts().template
module.exports = function (content) {
if (process.env.UNI_USING_COMPONENTS) {
return require('./template-new').call(this, content)
const filterTagName = getPlatformFilterTag() || ''
function parseFilterModules (filterModules) {
if (filterModules) {
return JSON.parse(Buffer.from(filterModules, 'base64').toString('ascii'))
}
return {}
}
module.exports = function (content) {
this.cacheable && this.cacheable()
const realResourcePath = path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)
const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options')
if (vueLoaderOptions) {
const globalUsingComponents = getGlobalUsingComponents()
const realResourcePath = path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)
const resourcePath = normalizeNodeModules(removeExt(realResourcePath) + templateExt)
const wxComponents = getWXComponents(resourcePath.replace(path.extname(resourcePath), ''))
if (process.env.UNI_USING_COMPONENTS) {
// 向 uni-template-compier 传递 emitFile
const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options')
if (vueLoaderOptions) {
Object.assign(vueLoaderOptions.options.compilerOptions, {
resourcePath: removeExt(realResourcePath) + templateExt,
emitFile: this.emitFile
})
} else {
throw new Error('vue-loader-options parse error')
}
const params = loaderUtils.parseQuery(this.resourceQuery)
/* eslint-disable no-mixed-operators */
const filterModules = parseFilterModules(params && params['filter-modules'])
Object.assign(vueLoaderOptions.options.compilerOptions, {
mp: {
platform: process.env.UNI_PLATFORM
},
filterModules,
filterTagName,
resourcePath,
emitFile: this.emitFile,
wxComponents,
getJsonFile,
getShadowTemplate,
updateSpecialMethods,
globalUsingComponents,
updateGenericComponents,
updateComponentGenerics,
updateUsingGlobalComponents
})
} else {
if (!content.trim()) {
content = '<view></view>'
}
cacheTemplate(realResourcePath, content)
const query = qs.parse(this.resourceQuery.slice(1))
const {
id
} = query
const compilerOptions = {
scopeId: query.scoped ? `data-v-${id}` : null,
target: getPlatformTarget(),
md5: md5(content.trim() + process.env.UNI_PLATFORM),
realResourcePath
}
cacheCompilerOptions(realResourcePath, compilerOptions)
// 向 vue-loader templateLoader 传递 compilerOptions
const vueLoaderOptions = this.loaders.find(loader => loader.ident === 'vue-loader-options')
if (vueLoaderOptions) {
Object.assign(vueLoaderOptions.options.compilerOptions, compilerOptions)
} else {
throw new Error('vue-loader-options parse error')
}
throw new Error('vue-loader-options parse error')
}
return content
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册