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

wip(i18n): titleText and tabBar

上级 318147aa
...@@ -350,6 +350,10 @@ var serviceContext = (function () { ...@@ -350,6 +350,10 @@ var serviceContext = (function () {
return typeof fn === 'function' return typeof fn === 'function'
} }
function isStr (str) {
return typeof str === 'string'
}
function isObject (obj) { function isObject (obj) {
return obj !== null && typeof obj === 'object' return obj !== null && typeof obj === 'object'
} }
...@@ -1465,6 +1469,9 @@ var serviceContext = (function () { ...@@ -1465,6 +1469,9 @@ var serviceContext = (function () {
}, },
}; };
} }
function isI18nStr(value, delimiters) {
return value.indexOf(delimiters[0]) > -1;
}
var en = { var en = {
"uni.app.quit": "Press back button again to exit", "uni.app.quit": "Press back button again to exit",
...@@ -1685,6 +1692,78 @@ var serviceContext = (function () { ...@@ -1685,6 +1692,78 @@ var serviceContext = (function () {
}); });
} }
const I18N_JSON_DELIMITERS = ['%', '%'];
function getLocaleMessage () {
const locale = uni.getLocale();
const locales = __uniConfig.locales;
return (
locales[locale] || locales[__uniConfig.fallbackLocale] || locales.en || {}
)
}
function formatI18n (message) {
if (isI18nStr(message, I18N_JSON_DELIMITERS)) {
return i18n.f(message, getLocaleMessage(), I18N_JSON_DELIMITERS)
}
return message
}
function resolveJsonObj (
jsonObj,
names
) {
if (names.length === 1) {
if (jsonObj) {
const value = jsonObj[names[0]];
if (isStr(value) && isI18nStr(value, I18N_JSON_DELIMITERS)) {
return jsonObj
}
}
return
}
const name = names.shift();
return resolveJsonObj(jsonObj && jsonObj[name], names)
}
function defineI18nProperties (
obj,
names
) {
return names.map((name) => defineI18nProperty(obj, name))
}
function defineI18nProperty (obj, names) {
const jsonObj = resolveJsonObj(obj, names);
if (!jsonObj) {
return false
}
const prop = names[names.length - 1];
let value = jsonObj[prop];
Object.defineProperty(jsonObj, prop, {
get () {
return formatI18n(value)
},
set (v) {
value = v;
}
});
return true
}
function isEnableLocale () {
return __uniConfig.locales && !!Object.keys(__uniConfig.locales).length
}
function initNavigationBarI18n (navigationBar) {
if (isEnableLocale()) {
return defineI18nProperties(navigationBar, [
['titleText'],
['searchInput', 'placeholder']
])
}
}
const setClipboardData = { const setClipboardData = {
beforeSuccess () { beforeSuccess () {
const title = t('uni.setClipboardData.success'); const title = t('uni.setClipboardData.success');
...@@ -8459,81 +8538,125 @@ var serviceContext = (function () { ...@@ -8459,81 +8538,125 @@ var serviceContext = (function () {
const WEBVIEW_REMOVED = 'webviewRemoved'; const WEBVIEW_REMOVED = 'webviewRemoved';
const WEBVIEW_ID_PREFIX = 'webviewId'; const WEBVIEW_ID_PREFIX = 'webviewId';
function createButtonOnClick (index) { function createButtonOnClick(index) {
return function onClick (btn) { return function onClick(btn) {
const pages = getCurrentPages(); const pages = getCurrentPages();
if (!pages.length) { if (!pages.length) {
return return;
} }
btn.index = index; btn.index = index;
const page = pages[pages.length - 1]; const page = pages[pages.length - 1];
page.$vm && page.$vm &&
page.$vm.__call_hook && page.$vm.__call_hook &&
page.$vm.__call_hook('onNavigationBarButtonTap', btn); page.$vm.__call_hook("onNavigationBarButtonTap", btn);
} };
} }
function parseTitleNViewButtons (titleNView) { function parseTitleNViewButtons(titleNView) {
const buttons = titleNView.buttons; const buttons = titleNView.buttons;
if (!Array.isArray(buttons)) { if (!Array.isArray(buttons)) {
return titleNView return titleNView;
} }
buttons.forEach((btn, index) => { buttons.forEach((btn, index) => {
btn.onclick = createButtonOnClick(index); btn.onclick = createButtonOnClick(index);
}); });
return titleNView return titleNView;
} }
function parseTitleNView (routeOptions) { function parseTitleNView(id, routeOptions) {
const windowOptions = routeOptions.window; const windowOptions = routeOptions.window;
const titleNView = windowOptions.titleNView; const titleNView = windowOptions.titleNView;
routeOptions.meta.statusBarStyle = windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light'; routeOptions.meta.statusBarStyle =
if ( // 无头 windowOptions.navigationBarTextStyle === "black" ? "dark" : "light";
if (
// 无头
titleNView === false || titleNView === false ||
titleNView === 'false' || titleNView === "false" ||
( (windowOptions.navigationStyle === "custom" &&
windowOptions.navigationStyle === 'custom' && !isPlainObject(titleNView)) ||
!isPlainObject(titleNView) (windowOptions.transparentTitle === "always" && !isPlainObject(titleNView))
) || (
windowOptions.transparentTitle === 'always' &&
!isPlainObject(titleNView)
)
) { ) {
return false return false;
} }
const titleImage = windowOptions.titleImage || ''; const titleImage = windowOptions.titleImage || "";
const transparentTitle = windowOptions.transparentTitle || 'none'; const transparentTitle = windowOptions.transparentTitle || "none";
const titleNViewTypeList = { const titleNViewTypeList = {
none: 'default', none: "default",
auto: 'transparent', auto: "transparent",
always: 'float' always: "float"
}; };
const navigationBarBackgroundColor = windowOptions.navigationBarBackgroundColor; const navigationBarBackgroundColor =
windowOptions.navigationBarBackgroundColor;
const ret = { const ret = {
autoBackButton: !routeOptions.meta.isQuit, autoBackButton: !routeOptions.meta.isQuit,
titleText: titleImage === '' ? windowOptions.navigationBarTitleText || '' : '', titleText:
titleColor: windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff', titleImage === "" ? windowOptions.navigationBarTitleText || "" : "",
titleColor:
windowOptions.navigationBarTextStyle === "black" ? "#000000" : "#ffffff",
type: titleNViewTypeList[transparentTitle], type: titleNViewTypeList[transparentTitle],
backgroundColor: (/^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) || navigationBarBackgroundColor === 'transparent') ? navigationBarBackgroundColor : '#f7f7f7', backgroundColor:
tags: titleImage === '' ? [] : [{ /^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) ||
tag: 'img', navigationBarBackgroundColor === "transparent"
? navigationBarBackgroundColor
: "#f7f7f7",
tags:
titleImage === ""
? []
: [
{
tag: "img",
src: titleImage, src: titleImage,
position: { position: {
left: 'auto', left: "auto",
top: 'auto', top: "auto",
width: 'auto', width: "auto",
height: '26px' height: "26px"
} }
}] }
]
}; };
if (isPlainObject(titleNView)) { if (isPlainObject(titleNView)) {
return Object.assign(ret, parseTitleNViewButtons(titleNView)) return initTitleNViewI18n(
id,
Object.assign(ret, parseTitleNViewButtons(titleNView))
);
}
return initTitleNViewI18n(id, ret);
} }
return ret function initTitleNViewI18n(id, titleNView) {
const i18nResult = initNavigationBarI18n(titleNView);
if (!i18nResult) {
return titleNView;
}
const [titleTextI18n, searchInputPlaceholderI18n] = i18nResult;
if (titleTextI18n || searchInputPlaceholderI18n) {
uni.onLocaleChange(() => {
const webview = plus.webview.getWebviewById(id + "");
if (!webview) {
return;
}
const newTitleNView = {};
if (titleTextI18n) {
newTitleNView.titleText = titleNView.titleText;
}
if (searchInputPlaceholderI18n) {
newTitleNView.searchInput = {
placeholder: titleNView.searchInput.placeholder
};
}
if (process.env.NODE_ENV !== "production") {
console.log("[uni-app] updateWebview", webview.id, newTitleNView);
}
webview.setStyle({
titleNView: newTitleNView
});
});
}
return titleNView;
} }
function parsePullToRefresh (routeOptions) { function parsePullToRefresh (routeOptions) {
...@@ -8624,10 +8747,12 @@ var serviceContext = (function () { ...@@ -8624,10 +8747,12 @@ var serviceContext = (function () {
}; };
// 合并 // 合并
routeOptions.window = parseStyleUnit(Object.assign( routeOptions.window = parseStyleUnit(
Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})), JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {} routeOptions.window || {}
)); )
);
Object.keys(routeOptions.window).forEach(name => { Object.keys(routeOptions.window).forEach(name => {
if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) { if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
...@@ -8636,7 +8761,10 @@ var serviceContext = (function () { ...@@ -8636,7 +8761,10 @@ var serviceContext = (function () {
}); });
const backgroundColor = routeOptions.window.backgroundColor; const backgroundColor = routeOptions.window.backgroundColor;
if (/^#[a-z0-9]{6}$/i.test(backgroundColor) || backgroundColor === 'transparent') { if (
/^#[a-z0-9]{6}$/i.test(backgroundColor) ||
backgroundColor === 'transparent'
) {
if (!webviewStyle.background) { if (!webviewStyle.background) {
webviewStyle.background = backgroundColor; webviewStyle.background = backgroundColor;
} }
...@@ -8645,7 +8773,7 @@ var serviceContext = (function () { ...@@ -8645,7 +8773,7 @@ var serviceContext = (function () {
} }
} }
const titleNView = parseTitleNView(routeOptions); const titleNView = parseTitleNView(id, routeOptions);
if (titleNView) { if (titleNView) {
if ( if (
id === 1 && id === 1 &&
...@@ -8670,7 +8798,8 @@ var serviceContext = (function () { ...@@ -8670,7 +8798,8 @@ var serviceContext = (function () {
delete webviewStyle.popGesture; delete webviewStyle.popGesture;
} }
if (routeOptions.meta.isQuit) { // 退出 if (routeOptions.meta.isQuit) {
// 退出
webviewStyle.popGesture = plus.os.name === 'iOS' ? 'appback' : 'none'; webviewStyle.popGesture = plus.os.name === 'iOS' ? 'appback' : 'none';
} }
......
...@@ -64,5 +64,7 @@ ...@@ -64,5 +64,7 @@
"pagesLoader.pagesNodeCannotNull": "Pages node in pages.json cannot be empty", "pagesLoader.pagesNodeCannotNull": "Pages node in pages.json cannot be empty",
"pagesLoader.nvueFirstPageStartModeIsFast": "Nvue homepage startup mode: fast. For details, see: {{0}}", "pagesLoader.nvueFirstPageStartModeIsFast": "Nvue homepage startup mode: fast. For details, see: {{0}}",
"pagesLoader.pagesTabbarMinItem2": "{{0}} must contain at least 2 items", "pagesLoader.pagesTabbarMinItem2": "{{0}} must contain at least 2 items",
"pagesLoader.needInPagesNode": "{{0}} needs to be in the pages array" "pagesLoader.needInPagesNode": "{{0}} needs to be in the pages array",
"i18n.fallbackLocale.default": "fallbackLocale is missing in manifest.json, use:{{locale}}",
"i18n.fallbackLocale.missing": "./local/{locale}.json is missing"
} }
...@@ -64,5 +64,7 @@ ...@@ -64,5 +64,7 @@
"pagesLoader.pagesNodeCannotNull": "pages.json 中的 pages 节点不能为空", "pagesLoader.pagesNodeCannotNull": "pages.json 中的 pages 节点不能为空",
"pagesLoader.nvueFirstPageStartModeIsFast": "Nvue 首页启动模式: fast, 详见: {{0}}", "pagesLoader.nvueFirstPageStartModeIsFast": "Nvue 首页启动模式: fast, 详见: {{0}}",
"pagesLoader.pagesTabbarMinItem2": "{{0}} 需至少包含2项", "pagesLoader.pagesTabbarMinItem2": "{{0}} 需至少包含2项",
"pagesLoader.needInPagesNode": "{{0}} 需在 pages 数组中" "pagesLoader.needInPagesNode": "{{0}} 需在 pages 数组中",
"i18n.fallbackLocale.default": "当前应用未在 manifest.json 配置 fallbackLocale,默认使用:{{locale}}",
"i18n.fallbackLocale.missing": "当前应用配置的 fallbackLocale 或 locale 为:{locale},但 locale 目录缺少该语言文件"
} }
const fs = require('fs')
const path = require('path')
const { parseJson } = require('./json')
const { getManifestJson } = require('./manifest')
const delimiters = ['%', '%']
function initI18nOptions (
platform,
inputDir,
warning = false,
withMessages = true
) {
const locales = initLocales(path.resolve(inputDir, 'locale'), withMessages)
if (!Object.keys(locales).length) {
return
}
const manifestJson = getManifestJson()
const fallbackLocale = manifestJson.fallbackLocale || manifestJson.locale
const locale = resolveI18nLocale(
platform,
Object.keys(locales),
fallbackLocale
)
if (warning) {
if (!fallbackLocale) {
console.warn()
} else if (locale !== fallbackLocale) {
console.warn()
}
}
return {
locale,
locales,
delimiters
}
}
function initLocales (dir, withMessages = true) {
if (!fs.existsSync(dir)) {
return {}
}
return fs.readdirSync(dir).reduce((res, filename) => {
if (path.extname(filename) === '.json') {
try {
res[path.basename(filename).replace('.json', '')] = withMessages
? parseJson(fs.readFileSync(path.join(dir, filename), 'utf8'))
: {}
} catch (e) {}
}
return res
}, {})
}
function resolveI18nLocale (platfrom, locales, locale) {
if (locale && locales.includes(locale)) {
return locale
}
const defaultLocales = ['zh-Hans', 'zh-Hant']
if (platfrom === 'app' || platfrom === 'h5') {
defaultLocales.unshift('en')
} else {
// 小程序
defaultLocales.push('en')
}
return defaultLocales.find(locale => locales.includes(locale)) || locales[0]
}
module.exports = {
initLocales,
initI18nOptions
}
因为 它太大了无法显示 source diff 。你可以改为 查看blob
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const { compileI18nJsonStr } = require('@dcloudio/uni-i18n')
const { initI18nOptions } = require('@dcloudio/uni-cli-shared/lib/i18n')
const assetsDir = 'static' const assetsDir = 'static'
function getAssetsCopyOption (from, options = {}) { function getAssetsCopyOption (from, options = {}) {
if (path.isAbsolute(from)) { if (path.isAbsolute(from)) {
if (fs.existsSync(from)) { if (fs.existsSync(from)) {
return Object.assign({ return Object.assign(
{
from, from,
to: path.resolve(process.env.UNI_OUTPUT_DIR) to: path.resolve(process.env.UNI_OUTPUT_DIR)
}, options) },
options
)
} }
} }
const to = from const to = from
from = path.resolve(process.env.UNI_INPUT_DIR, from) from = path.resolve(process.env.UNI_INPUT_DIR, from)
if (fs.existsSync(from)) { if (fs.existsSync(from)) {
return Object.assign({ return Object.assign(
{
from, from,
to: path.resolve(process.env.UNI_OUTPUT_DIR, to) to: path.resolve(process.env.UNI_OUTPUT_DIR, to)
}, options) },
options
)
} }
} }
// 暂未考虑动态添加static目录 // 暂未考虑动态添加static目录
...@@ -40,10 +47,14 @@ function getAssetsCopyOptions (assetsDir) { ...@@ -40,10 +47,14 @@ function getAssetsCopyOptions (assetsDir) {
copyOptions.push(mainAssetsCopyOption) copyOptions.push(mainAssetsCopyOption)
} }
// 分包静态资源 // 分包静态资源
process.UNI_SUBPACKAGES && Object.keys(process.UNI_SUBPACKAGES).forEach(root => { process.UNI_SUBPACKAGES &&
const subAssetsCopyOption = getAssetsCopyOption(path.join(root, assetsDir), { Object.keys(process.UNI_SUBPACKAGES).forEach(root => {
const subAssetsCopyOption = getAssetsCopyOption(
path.join(root, assetsDir),
{
ignore ignore
}) }
)
if (subAssetsCopyOption) { if (subAssetsCopyOption) {
copyOptions.push(subAssetsCopyOption) copyOptions.push(subAssetsCopyOption)
} }
...@@ -54,15 +65,20 @@ function getAssetsCopyOptions (assetsDir) { ...@@ -54,15 +65,20 @@ function getAssetsCopyOptions (assetsDir) {
function getUniModulesAssetsCopyOptions (assetsDir) { function getUniModulesAssetsCopyOptions (assetsDir) {
const copyOptions = [] const copyOptions = []
global.uniModules.forEach(module => { global.uniModules.forEach(module => {
copyOptions.push(...getAssetsCopyOptions('uni_modules/' + module + '/' + assetsDir)) copyOptions.push(
...getAssetsCopyOptions('uni_modules/' + module + '/' + assetsDir)
)
}) })
return copyOptions return copyOptions
} }
function getCopyWebpackPluginOptions (platformOptions, vueOptions) { function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
const copyOptions = getAssetsCopyOptions(assetsDir).concat(getUniModulesAssetsCopyOptions(assetsDir)) const copyOptions = getAssetsCopyOptions(assetsDir).concat(
getUniModulesAssetsCopyOptions(assetsDir)
)
global.uniPlugin.copyWebpackOptions.forEach(copyWebpackOptions => { global.uniPlugin.copyWebpackOptions.forEach(copyWebpackOptions => {
const platformCopyOptions = copyWebpackOptions(platformOptions, vueOptions, copyOptions) || [] const platformCopyOptions =
copyWebpackOptions(platformOptions, vueOptions, copyOptions) || []
platformCopyOptions.forEach(copyOption => { platformCopyOptions.forEach(copyOption => {
if (typeof copyOption === 'string') { if (typeof copyOption === 'string') {
copyOption = getAssetsCopyOption(copyOption) copyOption = getAssetsCopyOption(copyOption)
...@@ -76,6 +92,21 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) { ...@@ -76,6 +92,21 @@ function getCopyWebpackPluginOptions (platformOptions, vueOptions) {
to: '[name].[ext]', to: '[name].[ext]',
globOptions: { globOptions: {
ignored: require('./util').getWatchOptions().ignored ignored: require('./util').getWatchOptions().ignored
},
transform (content, path) {
if (path.endsWith('androidPrivacy.json')) {
const options = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
false,
true
)
if (!options) {
return content
}
return compileI18nJsonStr(content.toString(), options)
}
return content
} }
}) })
} }
......
const fs = require('fs') const fs = require("fs");
const path = require('path') const path = require("path");
const loaderUtils = require('loader-utils') const loaderUtils = require("loader-utils");
const { const {
parsePages, parsePages,
normalizePath, normalizePath,
parsePagesJson, parsePagesJson,
parseManifestJson parseManifestJson
} = require('@dcloudio/uni-cli-shared') } = require("@dcloudio/uni-cli-shared");
const { const {
updateAppJson, updateAppJson,
updatePageJson, updatePageJson,
updateProjectJson updateProjectJson
} = require('@dcloudio/uni-cli-shared/lib/cache') } = require("@dcloudio/uni-cli-shared/lib/cache");
const { const { initTheme, parseTheme } = require("@dcloudio/uni-cli-shared/lib/theme");
initTheme,
parseTheme
} = require('@dcloudio/uni-cli-shared/lib/theme')
const { const {
// pagesJsonJsFileName, // pagesJsonJsFileName,
initAutoImportComponents initAutoImportComponents
} = require('@dcloudio/uni-cli-shared/lib/pages') } = require("@dcloudio/uni-cli-shared/lib/pages");
const uniI18n = require("@dcloudio/uni-cli-i18n");
const uniI18n = require('@dcloudio/uni-cli-i18n') const parseStyle = require("./util").parseStyle;
const parseStyle = require('./util').parseStyle const { initI18nOptions } = require("@dcloudio/uni-cli-shared/lib/i18n");
const { parseI18nJson } = require("@dcloudio/uni-i18n");
// 将开发者手动设置的 usingComponents 调整名称,方便与自动解析到的 usingComponents 做最后合并 // 将开发者手动设置的 usingComponents 调整名称,方便与自动解析到的 usingComponents 做最后合并
function renameUsingComponents (jsonObj) { function renameUsingComponents(jsonObj) {
if (jsonObj.usingComponents) { if (jsonObj.usingComponents) {
jsonObj.customUsingComponents = jsonObj.usingComponents jsonObj.customUsingComponents = jsonObj.usingComponents;
delete jsonObj.usingComponents delete jsonObj.usingComponents;
} }
return jsonObj return jsonObj;
} }
module.exports = function (content, map) { module.exports = function(content, map) {
this.cacheable && this.cacheable() this.cacheable && this.cacheable();
initTheme() initTheme();
let isAppView = false let isAppView = false;
if (this.resourceQuery) { if (this.resourceQuery) {
const params = loaderUtils.parseQuery(this.resourceQuery) const params = loaderUtils.parseQuery(this.resourceQuery);
isAppView = params.type === 'view' isAppView = params.type === "view";
} }
// const pagesJsonJsPath = path.resolve(process.env.UNI_INPUT_DIR, pagesJsonJsFileName) // const pagesJsonJsPath = path.resolve(process.env.UNI_INPUT_DIR, pagesJsonJsFileName)
const manifestJsonPath = path.resolve(process.env.UNI_INPUT_DIR, 'manifest.json') const manifestJsonPath = path.resolve(
const manifestJson = parseManifestJson(fs.readFileSync(manifestJsonPath, 'utf8')) process.env.UNI_INPUT_DIR,
"manifest.json"
);
const manifestJson = parseManifestJson(
fs.readFileSync(manifestJsonPath, "utf8")
);
// this.addDependency(pagesJsonJsPath) // this.addDependency(pagesJsonJsPath)
this.addDependency(manifestJsonPath) this.addDependency(manifestJsonPath);
let pagesJson = parsePagesJson(content, { let pagesJson = parsePagesJson(content, {
addDependency: (file) => { addDependency: file => {
(process.UNI_PAGES_DEPS || (process.UNI_PAGES_DEPS = new Set())).add(normalizePath(file)) (process.UNI_PAGES_DEPS || (process.UNI_PAGES_DEPS = new Set())).add(
this.addDependency(file) normalizePath(file)
);
this.addDependency(file);
} }
}) });
if (!pagesJson.pages || pagesJson.pages.length === 0) { if (!pagesJson.pages || pagesJson.pages.length === 0) {
console.error(uniI18n.__('pagesLoader.pagesNodeCannotNull')) console.error(uniI18n.__("pagesLoader.pagesNodeCannotNull"));
process.exit(0) process.exit(0);
} }
if (global.uniPlugin.defaultTheme) { if (global.uniPlugin.defaultTheme) {
pagesJson = parseTheme(pagesJson) pagesJson = parseTheme(pagesJson);
this.addDependency(path.resolve(process.env.UNI_INPUT_DIR, 'theme.json')) this.addDependency(path.resolve(process.env.UNI_INPUT_DIR, "theme.json"));
} }
// 组件自动导入配置 // 组件自动导入配置
process.UNI_AUTO_SCAN_COMPONENTS = !(pagesJson.easycom && pagesJson.easycom.autoscan === false) process.UNI_AUTO_SCAN_COMPONENTS = !(
initAutoImportComponents(pagesJson.easycom) pagesJson.easycom && pagesJson.easycom.autoscan === false
);
initAutoImportComponents(pagesJson.easycom);
// TODO 与 usingComponents 放在一块读取设置 // TODO 与 usingComponents 放在一块读取设置
if (manifestJson.transformPx === false) { if (manifestJson.transformPx === false) {
process.UNI_TRANSFORM_PX = false process.UNI_TRANSFORM_PX = false;
} else { } else {
process.UNI_TRANSFORM_PX = true process.UNI_TRANSFORM_PX = true;
}
if (process.env.UNI_PLATFORM === "h5") {
return this.callback(
null,
require("./platforms/h5")(pagesJson, manifestJson, this),
map
);
}
if (process.env.UNI_PLATFORM === "quickapp-native") {
return this.callback(
null,
require("./platforms/quickapp-native")(pagesJson, manifestJson, this),
map
);
}
// 仅限小程序
if (process.env.UNI_PLATFORM !== "app-plus") {
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
true,
true
);
if (i18nOptions) {
const { locale, locales, delimiters } = i18nOptions;
parseI18nJson(pagesJson, locales[locale], delimiters);
} }
if (process.env.UNI_PLATFORM === 'h5') {
return this.callback(null, require('./platforms/h5')(pagesJson, manifestJson, this), map)
} }
if (process.env.UNI_PLATFORM === 'quickapp-native') {
return this.callback(null, require('./platforms/quickapp-native')(pagesJson, manifestJson, this), map)
}
if (!process.env.UNI_USING_V3) { if (!process.env.UNI_USING_V3) {
parsePages(pagesJson, function (page) { parsePages(
updatePageJson(page.path, renameUsingComponents(parseStyle(page.style))) pagesJson,
}, function (root, page) { function(page) {
updatePageJson(normalizePath(path.join(root, page.path)), renameUsingComponents( updatePageJson(
parseStyle(page.style, root) page.path,
)) renameUsingComponents(parseStyle(page.style))
}) );
} },
function(root, page) {
const jsonFiles = require('./platforms/' + process.env.UNI_PLATFORM)(pagesJson, manifestJson, isAppView) updatePageJson(
normalizePath(path.join(root, page.path)),
renameUsingComponents(parseStyle(page.style, root))
);
}
);
}
const jsonFiles = require("./platforms/" + process.env.UNI_PLATFORM)(
pagesJson,
manifestJson,
isAppView
);
if (jsonFiles && jsonFiles.length) { if (jsonFiles && jsonFiles.length) {
if (process.env.UNI_USING_V3) { if (process.env.UNI_USING_V3) {
let appConfigContent = '' let appConfigContent = "";
jsonFiles.forEach(jsonFile => { jsonFiles.forEach(jsonFile => {
if (jsonFile) { if (jsonFile) {
if (!isAppView && jsonFile.name === 'manifest.json') { if (!isAppView && jsonFile.name === "manifest.json") {
const content = JSON.parse(jsonFile.content) const content = JSON.parse(jsonFile.content);
if (!content.launch_path && content.plus['uni-app'].nvueLaunchMode === 'fast') { if (
console.log(uniI18n.__('pagesLoader.nvueFirstPageStartModeIsFast', { 0: 'https://ask.dcloud.net.cn/article/36749' })) !content.launch_path &&
content.plus["uni-app"].nvueLaunchMode === "fast"
) {
console.log(
uniI18n.__("pagesLoader.nvueFirstPageStartModeIsFast", {
0: "https://ask.dcloud.net.cn/article/36749"
})
);
} }
} }
if (jsonFile.name === 'define-pages.js') { if (jsonFile.name === "define-pages.js") {
appConfigContent = jsonFile.content appConfigContent = jsonFile.content;
} else { } else {
// app-view 不需要生成 app-config-service.js,manifest.json // app-view 不需要生成 app-config-service.js,manifest.json
!isAppView && this.emitFile(jsonFile.name, jsonFile.content) !isAppView && this.emitFile(jsonFile.name, jsonFile.content);
} }
} }
}) });
return this.callback(null, appConfigContent, map) return this.callback(null, appConfigContent, map);
} }
if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) { if (process.env.UNI_USING_NATIVE || process.env.UNI_USING_V3_NATIVE) {
let appConfigContent = '' let appConfigContent = "";
jsonFiles.forEach(jsonFile => { jsonFiles.forEach(jsonFile => {
if (jsonFile) { if (jsonFile) {
if (jsonFile.name === 'app-config.js' || jsonFile.name === 'define-pages.js') { if (
appConfigContent = jsonFile.content jsonFile.name === "app-config.js" ||
jsonFile.name === "define-pages.js"
) {
appConfigContent = jsonFile.content;
} else { } else {
this.emitFile(jsonFile.name, jsonFile.content) this.emitFile(jsonFile.name, jsonFile.content);
} }
} }
}) });
return this.callback(null, appConfigContent, map) return this.callback(null, appConfigContent, map);
} }
jsonFiles.forEach(jsonFile => { jsonFiles.forEach(jsonFile => {
if (jsonFile) { if (jsonFile) {
if (jsonFile.name === 'app') { if (jsonFile.name === "app") {
updateAppJson(jsonFile.name, renameUsingComponents(jsonFile.content)) updateAppJson(jsonFile.name, renameUsingComponents(jsonFile.content));
} else { } else {
updateProjectJson(jsonFile.name, jsonFile.content) updateProjectJson(jsonFile.name, jsonFile.content);
} }
} }
}) });
} }
this.callback(null, '', map) this.callback(null, "", map);
} };
const {
initI18nOptions
} = require('@dcloudio/uni-cli-shared/lib/i18n')
function parseRoutes (config) { function parseRoutes (config) {
const __uniRoutes = [] const __uniRoutes = []
/* eslint-disable no-mixed-operators */ /* eslint-disable no-mixed-operators */
const tabBarList = (config.tabBar && config.tabBar.list || []).map(item => item.pagePath) const tabBarList = ((config.tabBar && config.tabBar.list) || []).map(
item => item.pagePath
)
Object.keys(config.page).forEach(function (pagePath) { Object.keys(config.page).forEach(function (pagePath) {
const isTabBar = tabBarList.indexOf(pagePath) !== -1 const isTabBar = tabBarList.indexOf(pagePath) !== -1
const isQuit = isTabBar || (config.pages[0] === pagePath) const isQuit = isTabBar || config.pages[0] === pagePath
const isNVue = !!config.page[pagePath].nvue const isNVue = !!config.page[pagePath].nvue
const route = { const route = {
path: '/' + pagePath, path: '/' + pagePath,
...@@ -64,6 +70,17 @@ module.exports = function definePages (appJson) { ...@@ -64,6 +70,17 @@ module.exports = function definePages (appJson) {
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) { if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
appJson.automator = true appJson.automator = true
} }
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
false,
true
)
if (i18nOptions) {
appJson.locale = ''
appJson.fallbackLocale = i18nOptions.locale
appJson.locales = i18nOptions.locales
}
return { return {
name: 'app-config-service.js', name: 'app-config-service.js',
content: ` content: `
......
...@@ -3,18 +3,18 @@ const fsExtra = require('fs-extra') ...@@ -3,18 +3,18 @@ const fsExtra = require('fs-extra')
const path = require('path') const path = require('path')
const merge = require('merge') const merge = require('merge')
const { const { normalizePath, getFlexDirection } = require('@dcloudio/uni-cli-shared')
normalizePath, const { compileI18nJsonStr } = require('@dcloudio/uni-i18n')
getFlexDirection const { initI18nOptions } = require('@dcloudio/uni-cli-shared/lib/i18n')
} = require('@dcloudio/uni-cli-shared') const { hasOwn, parseStyle } = require('../../util')
const {
hasOwn,
parseStyle
} = require('../../util')
const wxPageOrientationMapping = { const wxPageOrientationMapping = {
auto: ['portrait-primary', 'portrait-secondary', 'landscape-primary', 'landscape-secondary'], auto: [
'portrait-primary',
'portrait-secondary',
'landscape-primary',
'landscape-secondary'
],
portrait: ['portrait-primary', 'portrait-secondary'], portrait: ['portrait-primary', 'portrait-secondary'],
landscape: ['landscape-primary', 'landscape-secondary'] landscape: ['landscape-primary', 'landscape-secondary']
} }
...@@ -58,13 +58,13 @@ function normalizeNetworkTimeout (appJson) { ...@@ -58,13 +58,13 @@ function normalizeNetworkTimeout (appJson) {
function updateFileFlag (appJson) { function updateFileFlag (appJson) {
// 已经不再根据文件识别,理论可废弃此处的逻辑 // 已经不再根据文件识别,理论可废弃此处的逻辑
if ( if (process.env.UNI_USING_V3 || process.env.UNI_USING_V3_NATIVE) {
process.env.UNI_USING_V3 ||
process.env.UNI_USING_V3_NATIVE
) {
return return
} }
const nvueCompilerFilePath = path.resolve(process.env.UNI_OUTPUT_DIR, '__uniappnvuecompiler.js') const nvueCompilerFilePath = path.resolve(
process.env.UNI_OUTPUT_DIR,
'__uniappnvuecompiler.js'
)
const nvueCompilerExists = fs.existsSync(nvueCompilerFilePath) const nvueCompilerExists = fs.existsSync(nvueCompilerFilePath)
if (appJson.nvueCompiler === 'uni-app') { if (appJson.nvueCompiler === 'uni-app') {
...@@ -77,7 +77,10 @@ function updateFileFlag (appJson) { ...@@ -77,7 +77,10 @@ function updateFileFlag (appJson) {
} }
} }
const rendererFilePath = path.resolve(process.env.UNI_OUTPUT_DIR, '__uniapprenderer.js') const rendererFilePath = path.resolve(
process.env.UNI_OUTPUT_DIR,
'__uniapprenderer.js'
)
const rendererExists = fs.existsSync(rendererFilePath) const rendererExists = fs.existsSync(rendererFilePath)
if (appJson.renderer === 'native') { if (appJson.renderer === 'native') {
...@@ -92,9 +95,7 @@ function updateFileFlag (appJson) { ...@@ -92,9 +95,7 @@ function updateFileFlag (appJson) {
} }
module.exports = function (pagesJson, userManifestJson, isAppView) { module.exports = function (pagesJson, userManifestJson, isAppView) {
const { const { app } = require('../mp')(pagesJson, userManifestJson)
app
} = require('../mp')(pagesJson, userManifestJson)
const manifest = { const manifest = {
name: 'manifest' name: 'manifest'
...@@ -109,7 +110,9 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -109,7 +110,9 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
const TABBAR_HEIGHT = 50 const TABBAR_HEIGHT = 50
let manifestJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, './manifest.json'), 'utf8')) let manifestJson = JSON.parse(
fs.readFileSync(path.resolve(__dirname, './manifest.json'), 'utf8')
)
// 状态栏 // 状态栏
manifestJson.plus.statusbar = { manifestJson.plus.statusbar = {
...@@ -120,7 +123,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -120,7 +123,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
// 用户配置覆盖默认配置 // 用户配置覆盖默认配置
manifestJson = merge.recursive( manifestJson = merge.recursive(
true, true,
manifestJson, { manifestJson,
{
id: userManifestJson.appid || '', id: userManifestJson.appid || '',
name: userManifestJson.name || '', name: userManifestJson.name || '',
description: userManifestJson.description || '', description: userManifestJson.description || '',
...@@ -129,14 +133,18 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -129,14 +133,18 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
code: userManifestJson.versionCode code: userManifestJson.versionCode
}, },
language: userManifestJson.locale language: userManifestJson.locale
}, { },
{
plus: userManifestJson['app-plus'] plus: userManifestJson['app-plus']
} }
) )
const splashscreenOptions = userManifestJson['app-plus'] && userManifestJson['app-plus'].splashscreen const splashscreenOptions =
userManifestJson['app-plus'] && userManifestJson['app-plus'].splashscreen
const hasAlwaysShowBeforeRender = splashscreenOptions && hasOwn(splashscreenOptions, 'alwaysShowBeforeRender') const hasAlwaysShowBeforeRender =
splashscreenOptions &&
hasOwn(splashscreenOptions, 'alwaysShowBeforeRender')
// 转换为老版本配置 // 转换为老版本配置
if (manifestJson.plus.modules) { if (manifestJson.plus.modules) {
...@@ -162,11 +170,14 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -162,11 +170,14 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
} }
// 屏幕启动方向 // 屏幕启动方向
if (manifestJson.plus.screenOrientation) { // app平台优先使用 manifest 配置 if (manifestJson.plus.screenOrientation) {
// app平台优先使用 manifest 配置
manifestJson.screenOrientation = manifestJson.plus.screenOrientation manifestJson.screenOrientation = manifestJson.plus.screenOrientation
delete manifestJson.plus.screenOrientation delete manifestJson.plus.screenOrientation
} else if (appJson.window && appJson.window.pageOrientation) { // 兼容微信小程序 } else if (appJson.window && appJson.window.pageOrientation) {
const pageOrientationValue = wxPageOrientationMapping[appJson.window.pageOrientation] // 兼容微信小程序
const pageOrientationValue =
wxPageOrientationMapping[appJson.window.pageOrientation]
if (pageOrientationValue) { if (pageOrientationValue) {
manifestJson.screenOrientation = pageOrientationValue manifestJson.screenOrientation = pageOrientationValue
} }
...@@ -184,14 +195,13 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -184,14 +195,13 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.permissions = {} manifestJson.permissions = {}
} }
const nvuePages = process.env.UNI_USING_V3_NATIVE ? pagesJson.pages : (pagesJson.nvue && pagesJson.nvue.pages) const nvuePages = process.env.UNI_USING_V3_NATIVE
? pagesJson.pages
: pagesJson.nvue && pagesJson.nvue.pages
if (nvuePages && nvuePages.length) { if (nvuePages && nvuePages.length) {
const pages = {} const pages = {}
nvuePages.forEach(({ nvuePages.forEach(({ path, style }) => {
path,
style
}) => {
pages[path] = { pages[path] = {
window: parseStyle(style), window: parseStyle(style),
nvue: true nvue: true
...@@ -259,7 +269,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -259,7 +269,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
} }
} }
} }
if (!process.env.UNI_USING_COMPONENTS) { // 非自定义组件模式下,仍旧添加 render always if (!process.env.UNI_USING_COMPONENTS) {
// 非自定义组件模式下,仍旧添加 render always
addRenderAlways() addRenderAlways()
} }
} else { } else {
...@@ -275,7 +286,9 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -275,7 +286,9 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
appJson.nvueCompiler = 'weex' appJson.nvueCompiler = 'weex'
} }
appJson.nvueStyleCompiler = process.env.UNI_USING_NVUE_STYLE_COMPILER ? 'uni-app' : 'weex' appJson.nvueStyleCompiler = process.env.UNI_USING_NVUE_STYLE_COMPILER
? 'uni-app'
: 'weex'
if (manifestJson.plus.renderer === 'native') { if (manifestJson.plus.renderer === 'native') {
appJson.renderer = 'native' appJson.renderer = 'native'
...@@ -292,10 +305,15 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -292,10 +305,15 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
// 强制白屏检测 // 强制白屏检测
if (manifestJson.plus.splashscreen) { if (manifestJson.plus.splashscreen) {
if (!hasAlwaysShowBeforeRender && manifestJson.plus.splashscreen.autoclose === false) { // 兼容旧版本仅配置了 autoclose 为 false if (
!hasAlwaysShowBeforeRender &&
manifestJson.plus.splashscreen.autoclose === false
) {
// 兼容旧版本仅配置了 autoclose 为 false
manifestJson.plus.splashscreen.alwaysShowBeforeRender = false manifestJson.plus.splashscreen.alwaysShowBeforeRender = false
} }
if (manifestJson.plus.splashscreen.alwaysShowBeforeRender) { // 白屏检测 if (manifestJson.plus.splashscreen.alwaysShowBeforeRender) {
// 白屏检测
if (!manifestJson.plus.splashscreen.target) { if (!manifestJson.plus.splashscreen.target) {
manifestJson.plus.splashscreen.target = 'id:1' manifestJson.plus.splashscreen.target = 'id:1'
} }
...@@ -303,10 +321,12 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -303,10 +321,12 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.plus.splashscreen.delay = 0 manifestJson.plus.splashscreen.delay = 0
appJson.splashscreen.alwaysShowBeforeRender = true appJson.splashscreen.alwaysShowBeforeRender = true
} else { // 不启用白屏检测 } else {
// 不启用白屏检测
delete manifestJson.plus.splashscreen.target delete manifestJson.plus.splashscreen.target
if (manifestJson.plus.splashscreen.autoclose) { // 启用 uni-app 框架关闭 splash if (manifestJson.plus.splashscreen.autoclose) {
// 启用 uni-app 框架关闭 splash
manifestJson.plus.splashscreen.autoclose = false // 原 5+ autoclose 改为 false manifestJson.plus.splashscreen.autoclose = false // 原 5+ autoclose 改为 false
appJson.splashscreen.autoclose = true appJson.splashscreen.autoclose = true
} }
...@@ -344,9 +364,14 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -344,9 +364,14 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
const resources = {} const resources = {}
const nvuePages = (appJson.nvue && appJson.nvue.pages) || {} const nvuePages = (appJson.nvue && appJson.nvue.pages) || {}
for (const key in confusion.resources) { for (const key in confusion.resources) {
if (path.extname(key) === '.js') { // 支持 js 混淆,过滤掉 if (path.extname(key) === '.js') {
// 支持 js 混淆,过滤掉
// 静态 js 文件 // 静态 js 文件
if (key.indexOf('hybrid/html') === 0 || key.indexOf('static/') === 0 || key.indexOf('/static/') !== -1) { if (
key.indexOf('hybrid/html') === 0 ||
key.indexOf('static/') === 0 ||
key.indexOf('/static/') !== -1
) {
resources[key] = confusion.resources[key] resources[key] = confusion.resources[key]
} }
continue continue
...@@ -356,22 +381,24 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -356,22 +381,24 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
} else { } else {
resources[key.replace(/\.nvue$/, '.js')] = confusion.resources[key] resources[key.replace(/\.nvue$/, '.js')] = confusion.resources[key]
} }
if (!Object.keys(nvuePages).find(path => { if (
!Object.keys(nvuePages).find(path => {
const subNVues = nvuePages[path].window.subNVues || [] const subNVues = nvuePages[path].window.subNVues || []
// TODO // TODO
return (path.replace(/\.html$/, '.nvue') === key || path.replace(/\.html$/, '.nvue') + '.nvue' === key) || return (
subNVues.find(({ path.replace(/\.html$/, '.nvue') === key ||
path path.replace(/\.html$/, '.nvue') + '.nvue' === key ||
}) => path === key.replace(/\.nvue$/, '')) subNVues.find(({ path }) => path === key.replace(/\.nvue$/, ''))
}) && !pagesJson.pages.find(({ )
style = {} }) &&
}) => { !pagesJson.pages.find(({ style = {} }) => {
style = Object.assign(style, style['app-plus']) style = Object.assign(style, style['app-plus'])
const subNVues = style.subNVues || [] const subNVues = style.subNVues || []
return subNVues.find(({ return subNVues.find(
path ({ path }) => path === key.replace(/\.nvue$/, '')
}) => path === key.replace(/\.nvue$/, '')) )
})) { })
) {
throw new Error(`原生混淆页面未在项目内使用,错误的页面路径:${key}`) throw new Error(`原生混淆页面未在项目内使用,错误的页面路径:${key}`)
} }
} }
...@@ -382,9 +409,12 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -382,9 +409,12 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
const uniApp = require('../../../package.json')['uni-app'] const uniApp = require('../../../package.json')['uni-app']
manifestJson.plus['uni-app'] = uniApp manifestJson.plus['uni-app'] = uniApp
// 控制页类型 // 控制页类型
const control = (process.env.UNI_USING_V3 || process.env.UNI_USING_V3_NATIVE) const control =
process.env.UNI_USING_V3 || process.env.UNI_USING_V3_NATIVE
? 'uni-v3' ? 'uni-v3'
: (process.env.UNI_USING_V8 ? 'v8' : 'webview') : process.env.UNI_USING_V8
? 'v8'
: 'webview'
manifestJson.plus['uni-app'].control = control manifestJson.plus['uni-app'].control = control
manifestJson.plus['uni-app'].nvueCompiler = appJson.nvueCompiler manifestJson.plus['uni-app'].nvueCompiler = appJson.nvueCompiler
...@@ -415,7 +445,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -415,7 +445,8 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
} }
let isNVueEntryPage = appJson.nvue && appJson.nvue.entryPagePath let isNVueEntryPage = appJson.nvue && appJson.nvue.entryPagePath
conditionPagePath = process.env.UNI_CLI_LAUNCH_PAGE_PATH || conditionPagePath conditionPagePath =
process.env.UNI_CLI_LAUNCH_PAGE_PATH || conditionPagePath
if (conditionPagePath && appJson.nvue) { if (conditionPagePath && appJson.nvue) {
isNVueEntryPage = `${conditionPagePath}.html` in appJson.nvue.pages isNVueEntryPage = `${conditionPagePath}.html` in appJson.nvue.pages
} }
...@@ -455,8 +486,15 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -455,8 +486,15 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.plus.launchwebview.render = 'always' manifestJson.plus.launchwebview.render = 'always'
} }
// 带 tab // 带 tab
if (pagesJson.tabBar && pagesJson.tabBar.list && pagesJson.tabBar.list.length) { if (
const tabBar = manifestJson.plus.tabBar = Object.assign({}, pagesJson.tabBar) pagesJson.tabBar &&
pagesJson.tabBar.list &&
pagesJson.tabBar.list.length
) {
const tabBar = (manifestJson.plus.tabBar = Object.assign(
{},
pagesJson.tabBar
))
const borderStyles = { const borderStyles = {
black: 'rgba(0,0,0,0.4)', black: 'rgba(0,0,0,0.4)',
white: 'rgba(255,255,255,0.4)' white: 'rgba(255,255,255,0.4)'
...@@ -477,13 +515,31 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -477,13 +515,31 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
manifestJson.plus.launchwebview.id = '2' manifestJson.plus.launchwebview.id = '2'
} else { } else {
// 首页是 tabBar 页面 // 首页是 tabBar 页面
const item = tabBar.list.find(page => page.pagePath === (process.env.UNI_USING_NATIVE ? appJson.entryPagePath const item = tabBar.list.find(
: entryPagePath)) page =>
page.pagePath ===
(process.env.UNI_USING_NATIVE
? appJson.entryPagePath
: entryPagePath)
)
if (item) { if (item) {
tabBar.child = ['lauchwebview'] tabBar.child = ['lauchwebview']
tabBar.selected = tabBar.list.indexOf(item) tabBar.selected = tabBar.list.indexOf(item)
} }
} }
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
true,
true
)
if (i18nOptions) {
manifestJson.plus.tabBar = JSON.parse(
compileI18nJsonStr(JSON.stringify(tabBar), i18nOptions)
)
manifestJson.fallbackLocale = i18nOptions.locale
}
} }
} }
...@@ -521,11 +577,16 @@ module.exports = function (pagesJson, userManifestJson, isAppView) { ...@@ -521,11 +577,16 @@ module.exports = function (pagesJson, userManifestJson, isAppView) {
if (process.env.UNI_USING_V3 && process.env.UNI_OPT_SUBPACKAGES) { if (process.env.UNI_USING_V3 && process.env.UNI_OPT_SUBPACKAGES) {
appJson.subPackages = subPackages appJson.subPackages = subPackages
} }
return require('./index.v3')(appJson, manifestJson, { return require('./index.v3')(
appJson,
manifestJson,
{
manifest, manifest,
pagesJson, pagesJson,
normalizeNetworkTimeout normalizeNetworkTimeout
}, isAppView) },
isAppView
)
} }
return [app, manifest] return [app, manifest]
} }
...@@ -444,7 +444,7 @@ module.exports = function (pagesJson, manifestJson, loader) { ...@@ -444,7 +444,7 @@ module.exports = function (pagesJson, manifestJson, loader) {
return ` return `
import Vue from 'vue' import Vue from 'vue'
${genLayoutComponentsCode(pagesJson)} ${genLayoutComponentsCode(pagesJson)}
const locales = ${fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'locale')) ? 'require.context(\'./locale\', false, /\.json$/)' : '{keys(){return []}}'} const locales = ${fs.existsSync(path.resolve(process.env.UNI_INPUT_DIR, 'locale')) ? 'require.context(\'./locale\', false, /.json$/)' : '{keys(){return []}}'}
global['____${h5.appid}____'] = true; global['____${h5.appid}____'] = true;
delete global['____${h5.appid}____']; delete global['____${h5.appid}____'];
global.__uniConfig = ${JSON.stringify(pagesJson)}; global.__uniConfig = ${JSON.stringify(pagesJson)};
......
...@@ -12,16 +12,9 @@ const { ...@@ -12,16 +12,9 @@ const {
updateAppJsonUsingComponents updateAppJsonUsingComponents
} = require('@dcloudio/uni-cli-shared/lib/cache') } = require('@dcloudio/uni-cli-shared/lib/cache')
const { const { darkmode, hasTheme } = require('@dcloudio/uni-cli-shared/lib/theme')
darkmode,
hasTheme
} = require('@dcloudio/uni-cli-shared/lib/theme')
const { const { hasOwn, parseStyle, trimMPJson } = require('../util')
hasOwn,
parseStyle,
trimMPJson
} = require('../util')
const uniI18n = require('@dcloudio/uni-cli-i18n') const uniI18n = require('@dcloudio/uni-cli-i18n')
...@@ -42,7 +35,9 @@ const pagesJson2AppJson = { ...@@ -42,7 +35,9 @@ const pagesJson2AppJson = {
tabBar: function (name, value, json, fromJson) { tabBar: function (name, value, json, fromJson) {
if (value && value.list && value.list.length) { if (value && value.list && value.list.length) {
if (value.list.length < 2) { if (value.list.length < 2) {
console.error(uniI18n.__('pagesLoader.pagesTabbarMinItem2', { 0: 'tabBar.list' })) console.error(
uniI18n.__('pagesLoader.pagesTabbarMinItem2', { 0: 'tabBar.list' })
)
} }
const pages = json.pages const pages = json.pages
value.list.forEach((page, index) => { value.list.forEach((page, index) => {
...@@ -52,12 +47,16 @@ const pagesJson2AppJson = { ...@@ -52,12 +47,16 @@ const pagesJson2AppJson = {
fromJson && fromJson &&
fromJson.nvue && fromJson.nvue &&
fromJson.nvue.pages && fromJson.nvue.pages &&
fromJson.nvue.pages.find(({ fromJson.nvue.pages.find(
path ({ path }) => path === page.pagePath + '.html'
}) => path === (page.pagePath + '.html')) )
) )
) { ) {
console.error(uniI18n.__('pagesLoader.needInPagesNode', { 0: `pages.json tabBar['list'][${index}]['pagePath'] "${page.pagePath}"` })) console.error(
uniI18n.__('pagesLoader.needInPagesNode', {
0: `pages.json tabBar['list'][${index}]['pagePath'] "${page.pagePath}"`
})
)
} }
} }
}) })
...@@ -74,7 +73,8 @@ const manifestJson2AppJson = { ...@@ -74,7 +73,8 @@ const manifestJson2AppJson = {
} }
function parseCondition (projectJson, pagesJson) { function parseCondition (projectJson, pagesJson) {
if (process.env.NODE_ENV === 'development') { // 仅开发期间 condition 生效 if (process.env.NODE_ENV === 'development') {
// 仅开发期间 condition 生效
// 启动Condition // 启动Condition
const condition = getCondition(pagesJson) const condition = getCondition(pagesJson)
if (condition) { if (condition) {
...@@ -89,7 +89,6 @@ function parseCondition (projectJson, pagesJson) { ...@@ -89,7 +89,6 @@ function parseCondition (projectJson, pagesJson) {
const pagesJson2ProjectJson = {} const pagesJson2ProjectJson = {}
const manifestJson2ProjectJson = { const manifestJson2ProjectJson = {
name: function (name, value, json) { name: function (name, value, json) {
if (!value) { if (!value) {
value = path.basename(process.env.UNI_INPUT_DIR) value = path.basename(process.env.UNI_INPUT_DIR)
...@@ -146,18 +145,26 @@ function getCondition (pagesJson) { ...@@ -146,18 +145,26 @@ function getCondition (pagesJson) {
delete item.path delete item.path
} }
if (launchPagePath) { if (launchPagePath) {
if (item.pathName === launchPagePath && item.query === launchPageQuery) { // 指定了入口页 if (
item.pathName === launchPagePath &&
item.query === launchPageQuery
) {
// 指定了入口页
current = index current = index
} }
} }
}) })
if (launchPagePath) { if (launchPagePath) {
if (current !== -1) { // 已存在 if (current !== -1) {
// 已存在
condition.current = current condition.current = current
} else { // 不存在 } else {
condition.list.push(Object.assign(launchPageOptions, { // 不存在
condition.list.push(
Object.assign(launchPageOptions, {
id: condition.list.length id: condition.list.length
})) })
)
condition.current = condition.list.length - 1 condition.current = condition.list.length - 1
} }
} }
...@@ -182,10 +189,14 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -182,10 +189,14 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
const subPackages = {} const subPackages = {}
parsePages(pagesJson, function (page) { parsePages(
pagesJson,
function (page) {
app.pages.push(page.path) app.pages.push(page.path)
}, function (root, page, subPackage) { },
if (!isSupportSubPackages()) { // 不支持分包 function (root, page, subPackage) {
if (!isSupportSubPackages()) {
// 不支持分包
app.pages.push(normalizePath(path.join(root, page.path))) app.pages.push(normalizePath(path.join(root, page.path)))
} else { } else {
if (!subPackages[root]) { if (!subPackages[root]) {
...@@ -201,7 +212,8 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -201,7 +212,8 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
} }
subPackages[root].pages.push(page.path) subPackages[root].pages.push(page.path)
} }
}) }
)
Object.keys(subPackages).forEach(root => { Object.keys(subPackages).forEach(root => {
app.subPackages.push(subPackages[root]) app.subPackages.push(subPackages[root])
...@@ -222,9 +234,12 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -222,9 +234,12 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
const projectName = getPlatformProject() const projectName = getPlatformProject()
const projectPath = projectName && path.resolve(process.env.VUE_CLI_CONTEXT || process.cwd(), projectName) const projectPath =
projectName &&
path.resolve(process.env.VUE_CLI_CONTEXT || process.cwd(), projectName)
if (projectPath && fs.existsSync(projectPath)) { // 自定义 project.config.json if (projectPath && fs.existsSync(projectPath)) {
// 自定义 project.config.json
const platform = process.env.UNI_PLATFORM const platform = process.env.UNI_PLATFORM
// app-plus时不需要处理平台配置到 app 中 // app-plus时不需要处理平台配置到 app 中
...@@ -235,7 +250,8 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -235,7 +250,8 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
Object.keys(platformJson).forEach(key => { Object.keys(platformJson).forEach(key => {
if ( if (
!projectKeys.includes(key) && ['usingComponents', 'optimization'].indexOf(key) === -1 !projectKeys.includes(key) &&
['usingComponents', 'optimization'].indexOf(key) === -1
) { ) {
// usingComponents 是编译模式开关,需要过滤,不能拷贝到 app // usingComponents 是编译模式开关,需要过滤,不能拷贝到 app
app[key] = platformJson[key] app[key] = platformJson[key]
...@@ -243,7 +259,11 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -243,7 +259,11 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
}) })
} }
if (process.env.UNI_PLATFORM === 'mp-weixin' || process.env.UNI_PLATFORM === 'mp-qq') { // 微信不需要生成,其他平台做拷贝 if (
process.env.UNI_PLATFORM === 'mp-weixin' ||
process.env.UNI_PLATFORM === 'mp-qq'
) {
// 微信不需要生成,其他平台做拷贝
return { return {
app: { app: {
name: 'app', name: 'app',
...@@ -279,7 +299,10 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -279,7 +299,10 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
const projectKeys = Object.keys(platformJson2ProjectJson) const projectKeys = Object.keys(platformJson2ProjectJson)
Object.keys(platformJson).forEach(key => { Object.keys(platformJson).forEach(key => {
if (!projectKeys.includes(key) && ['usingComponents', 'optimization'].indexOf(key) === -1) { if (
!projectKeys.includes(key) &&
['usingComponents', 'optimization'].indexOf(key) === -1
) {
// usingComponents 是编译模式开关,需要过滤,不能拷贝到 app // usingComponents 是编译模式开关,需要过滤,不能拷贝到 app
app[key] = platformJson[key] app[key] = platformJson[key]
} }
...@@ -287,7 +310,10 @@ module.exports = function (pagesJson, manifestJson, project = {}) { ...@@ -287,7 +310,10 @@ module.exports = function (pagesJson, manifestJson, project = {}) {
} }
// 引用了原生小程序组件,自动开启 ES6=>ES5 // 引用了原生小程序组件,自动开启 ES6=>ES5
const wxcomponentsPath = path.resolve(process.env.UNI_INPUT_DIR, './wxcomponents') const wxcomponentsPath = path.resolve(
process.env.UNI_INPUT_DIR,
'./wxcomponents'
)
if (fs.existsSync(wxcomponentsPath)) { if (fs.existsSync(wxcomponentsPath)) {
const wxcomponentsFiles = fs.readdirSync(wxcomponentsPath) const wxcomponentsFiles = fs.readdirSync(wxcomponentsPath)
if (wxcomponentsFiles.length) { if (wxcomponentsFiles.length) {
......
import { import { initVueI18n, isI18nStr } from '@dcloudio/uni-i18n'
initVueI18n, import { isStr } from 'uni-shared'
isI18nStr
} from '@dcloudio/uni-i18n'
import {
isStr
} from 'uni-shared'
import en from './en.json' import en from './en.json'
import es from './es.json' import es from './es.json'
...@@ -23,7 +18,7 @@ const messages = { ...@@ -23,7 +18,7 @@ const messages = {
let locale let locale
if (__PLATFORM__ === 'h5') { if (__PLATFORM__ === 'h5') {
locale = (__uniConfig.locale || navigator.language) locale = __uniConfig.locale || navigator.language
} else if (__PLATFORM__ === 'app-plus') { } else if (__PLATFORM__ === 'app-plus') {
if (typeof weex === 'object') { if (typeof weex === 'object') {
locale = weex.requireModule('plus').getLanguage() locale = weex.requireModule('plus').getLanguage()
...@@ -32,9 +27,12 @@ if (__PLATFORM__ === 'h5') { ...@@ -32,9 +27,12 @@ if (__PLATFORM__ === 'h5') {
locale = __GLOBAL__.getSystemInfoSync().language locale = __GLOBAL__.getSystemInfoSync().language
} }
export const i18n = initVueI18n(locale, __PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {}) export const i18n = initVueI18n(
locale,
__PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {}
)
export const t = i18n.t export const t = i18n.t
export const i18nMixin = i18n.mixin = { export const i18nMixin = (i18n.mixin = {
beforeCreate () { beforeCreate () {
const unwatch = i18n.i18n.watchLocale(() => { const unwatch = i18n.i18n.watchLocale(() => {
this.$forceUpdate() this.$forceUpdate()
...@@ -48,7 +46,7 @@ export const i18nMixin = i18n.mixin = { ...@@ -48,7 +46,7 @@ export const i18nMixin = i18n.mixin = {
return t(key, values) return t(key, values)
} }
} }
} })
export const setLocale = i18n.setLocale export const setLocale = i18n.setLocale
export const getLocale = i18n.getLocale export const getLocale = i18n.getLocale
...@@ -57,7 +55,7 @@ export function initAppLocale (Vue, appVm, locale) { ...@@ -57,7 +55,7 @@ export function initAppLocale (Vue, appVm, locale) {
locale: locale || i18n.getLocale() locale: locale || i18n.getLocale()
}) })
const localeWatchers = [] const localeWatchers = []
appVm.$watchLocale = (fn) => { appVm.$watchLocale = fn => {
localeWatchers.push(fn) localeWatchers.push(fn)
} }
Object.defineProperty(appVm, '$locale', { Object.defineProperty(appVm, '$locale', {
...@@ -88,10 +86,7 @@ export function formatI18n (message) { ...@@ -88,10 +86,7 @@ export function formatI18n (message) {
return message return message
} }
function resolveJsonObj ( function resolveJsonObj (jsonObj, names) {
jsonObj,
names
) {
if (names.length === 1) { if (names.length === 1) {
if (jsonObj) { if (jsonObj) {
const value = jsonObj[names[0]] const value = jsonObj[names[0]]
...@@ -105,11 +100,8 @@ function resolveJsonObj ( ...@@ -105,11 +100,8 @@ function resolveJsonObj (
return resolveJsonObj(jsonObj && jsonObj[name], names) return resolveJsonObj(jsonObj && jsonObj[name], names)
} }
export function defineI18nProperties ( export function defineI18nProperties (obj, names) {
obj, return names.map(name => defineI18nProperty(obj, name))
names
) {
return names.map((name) => defineI18nProperty(obj, name))
} }
export function defineI18nProperty (obj, names) { export function defineI18nProperty (obj, names) {
...@@ -143,9 +135,7 @@ export function initNavigationBarI18n (navigationBar) { ...@@ -143,9 +135,7 @@ export function initNavigationBarI18n (navigationBar) {
} }
} }
export function initPullToRefreshI18n ( export function initPullToRefreshI18n (pullToRefresh) {
pullToRefresh
) {
if (isEnableLocale()) { if (isEnableLocale()) {
const CAPTION = 'caption' const CAPTION = 'caption'
return defineI18nProperties(pullToRefresh, [ return defineI18nProperties(pullToRefresh, [
...@@ -155,3 +145,12 @@ export function initPullToRefreshI18n ( ...@@ -155,3 +145,12 @@ export function initPullToRefreshI18n (
]) ])
} }
} }
export function initTabBarI18n (tabBar) {
if (isEnableLocale()) {
tabBar.list.forEach(item => {
defineI18nProperty(item, ['text'])
})
}
return tabBar
}
import { import { isPlainObject } from 'uni-shared'
isPlainObject
} import { initNavigationBarI18n } from 'uni-helpers/i18n'
from 'uni-shared'
function createButtonOnClick (index) { function createButtonOnClick (index) {
return function onClick (btn) { return function onClick (btn) {
...@@ -28,20 +27,18 @@ function parseTitleNViewButtons (titleNView) { ...@@ -28,20 +27,18 @@ function parseTitleNViewButtons (titleNView) {
return titleNView return titleNView
} }
export function parseTitleNView (routeOptions) { export function parseTitleNView (id, routeOptions) {
const windowOptions = routeOptions.window const windowOptions = routeOptions.window
const titleNView = windowOptions.titleNView const titleNView = windowOptions.titleNView
routeOptions.meta.statusBarStyle = windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light' routeOptions.meta.statusBarStyle =
if ( // 无头 windowOptions.navigationBarTextStyle === 'black' ? 'dark' : 'light'
if (
// 无头
titleNView === false || titleNView === false ||
titleNView === 'false' || titleNView === 'false' ||
( (windowOptions.navigationStyle === 'custom' &&
windowOptions.navigationStyle === 'custom' && !isPlainObject(titleNView)) ||
!isPlainObject(titleNView) (windowOptions.transparentTitle === 'always' && !isPlainObject(titleNView))
) || (
windowOptions.transparentTitle === 'always' &&
!isPlainObject(titleNView)
)
) { ) {
return false return false
} }
...@@ -54,14 +51,25 @@ export function parseTitleNView (routeOptions) { ...@@ -54,14 +51,25 @@ export function parseTitleNView (routeOptions) {
always: 'float' always: 'float'
} }
const navigationBarBackgroundColor = windowOptions.navigationBarBackgroundColor const navigationBarBackgroundColor =
windowOptions.navigationBarBackgroundColor
const ret = { const ret = {
autoBackButton: !routeOptions.meta.isQuit, autoBackButton: !routeOptions.meta.isQuit,
titleText: titleImage === '' ? windowOptions.navigationBarTitleText || '' : '', titleText:
titleColor: windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff', titleImage === '' ? windowOptions.navigationBarTitleText || '' : '',
titleColor:
windowOptions.navigationBarTextStyle === 'black' ? '#000000' : '#ffffff',
type: titleNViewTypeList[transparentTitle], type: titleNViewTypeList[transparentTitle],
backgroundColor: (/^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) || navigationBarBackgroundColor === 'transparent') ? navigationBarBackgroundColor : '#f7f7f7', backgroundColor:
tags: titleImage === '' ? [] : [{ /^#[a-z0-9]{6}$/i.test(navigationBarBackgroundColor) ||
navigationBarBackgroundColor === 'transparent'
? navigationBarBackgroundColor
: '#f7f7f7',
tags:
titleImage === ''
? []
: [
{
tag: 'img', tag: 'img',
src: titleImage, src: titleImage,
position: { position: {
...@@ -70,12 +78,47 @@ export function parseTitleNView (routeOptions) { ...@@ -70,12 +78,47 @@ export function parseTitleNView (routeOptions) {
width: 'auto', width: 'auto',
height: '26px' height: '26px'
} }
}] }
]
} }
if (isPlainObject(titleNView)) { if (isPlainObject(titleNView)) {
return Object.assign(ret, parseTitleNViewButtons(titleNView)) return initTitleNViewI18n(
id,
Object.assign(ret, parseTitleNViewButtons(titleNView))
)
} }
return initTitleNViewI18n(id, ret)
}
return ret function initTitleNViewI18n (id, titleNView) {
const i18nResult = initNavigationBarI18n(titleNView)
if (!i18nResult) {
return titleNView
}
const [titleTextI18n, searchInputPlaceholderI18n] = i18nResult
if (titleTextI18n || searchInputPlaceholderI18n) {
uni.onLocaleChange(() => {
const webview = plus.webview.getWebviewById(id + '')
if (!webview) {
return
}
const newTitleNView = {}
if (titleTextI18n) {
newTitleNView.titleText = titleNView.titleText
}
if (searchInputPlaceholderI18n) {
newTitleNView.searchInput = {
placeholder: titleNView.searchInput.placeholder
}
}
if (process.env.NODE_ENV !== 'production') {
console.log('[uni-app] updateWebview', webview.id, newTitleNView)
}
webview.setStyle({
titleNView: newTitleNView
})
})
}
return titleNView
} }
import { import { parseTitleNView } from './title-nview-parser'
parseTitleNView
} from './title-nview-parser'
import { import { parsePullToRefresh } from './pull-to-refresh-parser'
parsePullToRefresh
} from './pull-to-refresh-parser'
import { import { parseStyleUnit } from './style-unit-parser'
parseStyleUnit
} from './style-unit-parser'
const WEBVIEW_STYLE_BLACKLIST = [ const WEBVIEW_STYLE_BLACKLIST = [
'navigationBarBackgroundColor', 'navigationBarBackgroundColor',
...@@ -33,10 +27,12 @@ export function parseWebviewStyle (id, path, routeOptions = {}) { ...@@ -33,10 +27,12 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
} }
// 合并 // 合并
routeOptions.window = parseStyleUnit(Object.assign( routeOptions.window = parseStyleUnit(
Object.assign(
JSON.parse(JSON.stringify(__uniConfig.window || {})), JSON.parse(JSON.stringify(__uniConfig.window || {})),
routeOptions.window || {} routeOptions.window || {}
)) )
)
Object.keys(routeOptions.window).forEach(name => { Object.keys(routeOptions.window).forEach(name => {
if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) { if (WEBVIEW_STYLE_BLACKLIST.indexOf(name) === -1) {
...@@ -45,7 +41,10 @@ export function parseWebviewStyle (id, path, routeOptions = {}) { ...@@ -45,7 +41,10 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
}) })
const backgroundColor = routeOptions.window.backgroundColor const backgroundColor = routeOptions.window.backgroundColor
if (/^#[a-z0-9]{6}$/i.test(backgroundColor) || backgroundColor === 'transparent') { if (
/^#[a-z0-9]{6}$/i.test(backgroundColor) ||
backgroundColor === 'transparent'
) {
if (!webviewStyle.background) { if (!webviewStyle.background) {
webviewStyle.background = backgroundColor webviewStyle.background = backgroundColor
} }
...@@ -54,7 +53,7 @@ export function parseWebviewStyle (id, path, routeOptions = {}) { ...@@ -54,7 +53,7 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
} }
} }
const titleNView = parseTitleNView(routeOptions) const titleNView = parseTitleNView(id, routeOptions)
if (titleNView) { if (titleNView) {
if ( if (
id === 1 && id === 1 &&
...@@ -79,7 +78,8 @@ export function parseWebviewStyle (id, path, routeOptions = {}) { ...@@ -79,7 +78,8 @@ export function parseWebviewStyle (id, path, routeOptions = {}) {
delete webviewStyle.popGesture delete webviewStyle.popGesture
} }
if (routeOptions.meta.isQuit) { // 退出 if (routeOptions.meta.isQuit) {
// 退出
webviewStyle.popGesture = plus.os.name === 'iOS' ? 'appback' : 'none' webviewStyle.popGesture = plus.os.name === 'iOS' ? 'appback' : 'none'
} }
......
import Vue from 'vue' import Vue from 'vue'
__uniConfig.tabBar = Vue.observable(__uniConfig.tabBar || {}) import { initTabBarI18n } from 'uni-helpers/i18n'
__uniConfig.tabBar = Vue.observable(initTabBarI18n(__uniConfig.tabBar || {}))
export const tabBar = __uniConfig.tabBar export const tabBar = __uniConfig.tabBar
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册