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

chore: add logs

上级 22557cc8
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const plugin_1 = require("./plugin");
const template_1 = require("./plugins/template");
const mainJs_1 = require("./plugins/mainJs");
const manifestJson_1 = require("./plugins/manifestJson");
const pagesJson_1 = require("./plugins/pagesJson");
const resolveId_1 = require("./plugins/resolveId");
const renderjs_1 = require("./plugins/renderjs");
function initUniCssScopedPluginOptions() {
const styleIsolation = uni_cli_shared_1.getAppStyleIsolation(uni_cli_shared_1.parseManifestJsonOnce(process.env.UNI_INPUT_DIR));
if (styleIsolation === 'shared') {
return;
}
if (styleIsolation === 'isolated') {
// isolated: 对所有非 App.vue 增加 scoped
return {};
}
// apply-shared: 仅对非页面组件增加 scoped
return { exclude: /mpType=page/ };
}
const plugins = [
resolveId_1.uniResolveIdPlugin(),
mainJs_1.uniMainJsPlugin(),
manifestJson_1.uniManifestJsonPlugin(),
pagesJson_1.uniPagesJsonPlugin(),
uni_cli_shared_1.uniViteInjectPlugin(uni_cli_shared_1.initProvide()),
renderjs_1.uniRenderjsPlugin(),
template_1.uniTemplatePlugin(),
plugin_1.UniAppPlugin,
];
const uniCssScopedPluginOptions = initUniCssScopedPluginOptions();
if (uniCssScopedPluginOptions) {
plugins.unshift(uni_cli_shared_1.uniCssScopedPlugin(uniCssScopedPluginOptions));
}
exports.default = plugins;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildOptions = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function buildOptions() {
// 开始编译时,清空输出目录
if (fs_1.default.existsSync(process.env.UNI_OUTPUT_DIR)) {
uni_cli_shared_1.emptyDir(process.env.UNI_OUTPUT_DIR);
}
return {
emptyOutDir: false,
assetsInlineLimit: 0,
rollupOptions: {
input: uni_cli_shared_1.resolveMainPathOnce(process.env.UNI_INPUT_DIR),
external: ['vue'],
output: {
name: 'AppService',
format: process.env.UNI_APP_CODE_SPLITING ? 'amd' : 'iife',
entryFileNames: 'app-service.js',
manualChunks: {},
chunkFileNames(chunk) {
if (chunk.isDynamicEntry && chunk.facadeModuleId) {
const filepath = path_1.default.relative(process.env.UNI_INPUT_DIR, chunk.facadeModuleId);
return uni_cli_shared_1.normalizePath(filepath.replace(path_1.default.extname(filepath), '.js'));
}
return '[name].js';
},
assetFileNames: '[name][extname]',
globals: {
vue: 'Vue',
},
},
},
};
}
exports.buildOptions = buildOptions;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.configResolved = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const configResolved = (config) => {
uni_cli_shared_1.removePlugins('vite:import-analysis', config);
uni_cli_shared_1.injectCssPlugin(config);
uni_cli_shared_1.injectCssPostPlugin(config);
uni_cli_shared_1.injectAssetPlugin(config);
};
exports.configResolved = configResolved;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UniAppPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const uni_1 = require("./uni");
const build_1 = require("./build");
const configResolved_1 = require("./configResolved");
exports.UniAppPlugin = {
name: 'vite:uni-app',
uni: uni_1.uniOptions(),
config() {
return {
build: build_1.buildOptions(),
};
},
configResolved: configResolved_1.configResolved,
resolveId(id) {
if (id === 'vue') {
return uni_cli_shared_1.resolveBuiltIn('@dcloudio/uni-app-vue');
}
},
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniOptions = void 0;
const uni_shared_1 = require("@dcloudio/uni-shared");
function uniOptions() {
return {
copyOptions() {
return {
assets: [
'androidPrivacy.json',
'hybrid/html/**/*',
'uni_modules/*/hybrid/html/**/*',
],
};
},
compilerOptions: {
isNativeTag: uni_shared_1.isServiceNativeTag,
isCustomElement: uni_shared_1.isServiceCustomElement,
},
transformEvent: {
tap: 'click',
},
};
}
exports.uniOptions = uniOptions;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformRenderjs = void 0;
const transformRenderjs = () => { };
exports.transformRenderjs = transformRenderjs;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMainJsPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniMainJsPlugin() {
return uni_cli_shared_1.defineUniMainJsPlugin((opts) => {
return {
name: 'vite:uni-app-main-js',
enforce: 'pre',
transform(code, id) {
if (opts.filter(id)) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code);
return {
code: `import './pages.json.js';` + code,
map: this.getCombinedSourcemap(),
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `const __app__=createApp().app;__app__._component.mpType='app';__app__._component.render=()=>{};__app__.use(uni.__vuePlugin).mount("#app");${code.replace('createSSRApp', 'createVueApp as createSSRApp')}`;
}
function createLegacyApp(code) {
return `function createApp(rootComponent,rootProps){rootComponent.mpTye='app';const app=createVueApp(rootComponent,rootProps).use(uni.__vuePlugin);app.render=()=>{};const oldMount=app.mount;app.mount=(container)=>{const appVm=oldMount.call(app,container);return appVm;};return app;};${code.replace('createApp', 'createVueApp')}`;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniManifestJsonPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniManifestJsonPlugin() {
let manifestJson;
return uni_cli_shared_1.defineUniManifestJsonPlugin((opts) => {
return {
name: 'vite:uni-app-manifest-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return;
}
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'manifest.json'));
manifestJson = uni_cli_shared_1.normalizeAppManifestJson(uni_cli_shared_1.parseJson(code), uni_cli_shared_1.parsePagesJsonOnce(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM));
return '';
},
generateBundle() {
// 生成一个空的app-config.js,兼容基座已有规范
this.emitFile({
fileName: `app-config.js`,
type: 'asset',
source: '(function(){})();',
});
this.emitFile({
fileName: `manifest.json`,
type: 'asset',
source: JSON.stringify(manifestJson, null, 2),
});
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPagesJsonPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniPagesJsonPlugin() {
let pagesJson;
return uni_cli_shared_1.defineUniPagesJsonPlugin((opts) => {
return {
name: 'vite:uni-app-pages-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return;
}
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json'));
pagesJson = uni_cli_shared_1.normalizePagesJson(code, process.env.UNI_PLATFORM);
// TODO subpackages
pagesJson.pages.forEach((page) => {
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, page.path + '.vue'));
});
return (`import './manifest.json.js'\n` + uni_cli_shared_1.normalizeAppPagesJson(pagesJson));
},
generateBundle() {
this.emitFile({
fileName: `app-config-service.js`,
type: 'asset',
source: uni_cli_shared_1.normalizeAppConfigService(pagesJson, uni_cli_shared_1.parseManifestJsonOnce(process.env.UNI_INPUT_DIR)),
});
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniRenderjsPlugin = exports.APP_RENDERJS_JS = exports.APP_WXS_JS = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugRenderjs = debug_1.default('vite:uni:renderjs');
exports.APP_WXS_JS = 'app-wxs.js';
exports.APP_RENDERJS_JS = 'app-renderjs.js';
const wxsModulesCache = new WeakMap();
const renderjsModulesCache = new WeakMap();
function uniRenderjsPlugin() {
let resolvedConfig;
let changed = false;
return {
name: 'vite:uni-app-renderjs',
configResolved(config) {
resolvedConfig = config;
wxsModulesCache.set(resolvedConfig, new Map());
renderjsModulesCache.set(resolvedConfig, new Map());
},
async transform(code, id) {
const { type, name } = uni_cli_shared_1.parseRenderjs(id);
if (!type) {
return;
}
debugRenderjs(id);
if (!name) {
this.error(uni_cli_shared_1.missingModuleName(type, code));
}
const modulePath = uni_cli_shared_1.normalizePath(path_1.default.normalize(path_1.default.relative(process.env.UNI_INPUT_DIR, id)));
const moduleHashId = uni_cli_shared_1.hash(modulePath);
const globalName = type === 'wxs' ? uni_shared_1.WXS_MODULES : uni_shared_1.RENDERJS_MODULES;
const { isProduction } = resolvedConfig;
const res = type === 'wxs'
? await transformWxs(code, `__${globalName}['${moduleHashId}']`, isProduction)
: await transformRenderjs(code, `__${globalName}['${moduleHashId}']`, isProduction);
const resultCode = normalizeCode(res.code, globalName, isProduction);
if (type === 'wxs') {
wxsModulesCache.get(resolvedConfig).set(moduleHashId, resultCode);
}
else {
renderjsModulesCache.get(resolvedConfig).set(moduleHashId, resultCode);
}
changed = true;
debugRenderjs(type, modulePath, moduleHashId);
return `export default Comp => {
;(Comp.$${type} || (Comp.$${type} = [])).push('${name}')
;(Comp.$${globalName} || (Comp.$${globalName} = {}))['${name}'] = '${moduleHashId}'
}`;
},
generateBundle() {
if (!changed) {
return;
}
const wxsCode = [...wxsModulesCache.get(resolvedConfig).values()].join('\n');
if (wxsCode) {
this.emitFile({
fileName: exports.APP_WXS_JS,
source: `var __${uni_shared_1.WXS_MODULES}={};\n` + wxsCode,
type: 'asset',
});
}
const renderjsCode = [
...renderjsModulesCache.get(resolvedConfig).values(),
].join('\n');
if (renderjsCode) {
this.emitFile({
fileName: exports.APP_RENDERJS_JS,
source: `var __${uni_shared_1.RENDERJS_MODULES}={};\n` + renderjsCode,
type: 'asset',
});
}
},
};
}
exports.uniRenderjsPlugin = uniRenderjsPlugin;
function normalizeCode(code, globalName, isProduction) {
return code.replace(isProduction
? `var __${globalName}=__${globalName}||{};`
: `var __${globalName} = __${globalName} || {};`, '');
}
function transformWxs(code, globalName, isProduction) {
return uni_cli_shared_1.transformWithEsbuild(code, {
format: 'iife',
globalName,
minify: isProduction ? true : false,
});
}
function transformRenderjs(code, globalName, isProduction) {
return uni_cli_shared_1.transformWithEsbuild(code, {
format: 'iife',
globalName,
minify: isProduction ? true : false,
});
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniResolveIdPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugResolve = debug_1.default('vite:uni:resolve');
function uniResolveIdPlugin() {
const resolveCache = {};
return {
name: 'vite:uni-app-resolve-id',
enforce: 'pre',
configResolved() {
resolveCache['@dcloudio/uni-app-vue'] = uni_cli_shared_1.resolveBuiltIn('@dcloudio/uni-app-vue');
},
resolveId(id) {
if (id === 'vue') {
id = '@dcloudio/uni-app-vue';
}
const cache = resolveCache[id];
if (cache) {
debugResolve('cache', id, cache);
return cache;
}
},
};
}
exports.uniResolveIdPlugin = uniResolveIdPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniTemplatePlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const renderjs_1 = require("./renderjs");
function genViewHtml(bundle) {
const viewHtmlStr = fs_extra_1.default.readFileSync(path_1.default.resolve(__dirname, '../../lib/template/__uniappview.html'), 'utf8');
const { globalStyle } = uni_cli_shared_1.parsePagesJsonOnce(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
const __uniConfig = {
globalStyle: {
rpxCalcMaxDeviceWidth: globalStyle.rpxCalcMaxDeviceWidth,
rpxCalcBaseDeviceWidth: globalStyle.rpxCalcBaseDeviceWidth,
},
};
const wxsCode = bundle[renderjs_1.APP_WXS_JS]
? `<script src="${renderjs_1.APP_WXS_JS}"></script>`
: '';
const renderjsCode = bundle[renderjs_1.APP_RENDERJS_JS]
? `<script src="${renderjs_1.APP_RENDERJS_JS}"></script>`
: '';
return viewHtmlStr
.toString()
.replace('<!--wxsCode-->', wxsCode)
.replace('<!--renderjsCode-->', renderjsCode)
.replace('/*__uniConfig*/', `var __uniConfig = ${JSON.stringify(__uniConfig)}`);
}
function uniTemplatePlugin() {
let outputDir;
return {
name: 'vite:uni-app-template',
enforce: 'post',
configResolved() {
outputDir = process.env.UNI_OUTPUT_DIR;
fs_extra_1.default.copySync(require.resolve('@dcloudio/uni-app-plus/dist/uni-app-view.umd.js'), path_1.default.resolve(outputDir, 'uni-app-view.umd.js'), {
overwrite: true,
});
fs_extra_1.default.copySync(path_1.default.resolve(__dirname, '../../lib/template/'), outputDir, {
overwrite: true,
filter(src) {
return !src.includes('__uniappview.html');
},
});
},
generateBundle(_, bundle) {
this.emitFile({
fileName: '__uniappview.html',
source: genViewHtml(bundle),
type: 'asset',
});
},
};
}
exports.uniTemplatePlugin = uniTemplatePlugin;
import { UniVitePlugin, resolveBuiltIn } from '@dcloudio/uni-cli-shared'
import { M, UniVitePlugin, resolveBuiltIn } from '@dcloudio/uni-cli-shared'
import { uniOptions } from './uni'
import { buildOptions } from './build'
......@@ -8,6 +8,13 @@ export const UniAppPlugin: UniVitePlugin = {
name: 'vite:uni-app',
uni: uniOptions(),
config() {
const pkg = require('@dcloudio/vite-plugin-uni/package.json')
console.log(
M['app.compiler.version'].replace(
'{version}',
pkg['uni-app']['compilerVersion'] + '(vue3)'
)
)
return {
build: buildOptions(),
}
......
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* 注意:该包的依赖包含了 lib 中三方包的依赖
*/
__exportStar(require("./webpack"), exports);
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const webpack_1 = require("./webpack");
const UniAppNVuePlugin = () => {
let pagesJsonPath;
let watching;
let lastNVueEntry;
let isPagesJsonChanged = false;
return {
name: 'vite:uni-cli-nvue',
config() {
if (process.env.UNI_NVUE_COMPILER === 'vue') {
return;
}
pagesJsonPath = uni_cli_shared_1.normalizePath(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json'));
if (process.env.NODE_ENV === 'production') {
return webpack_1.runWebpackBuild().then(() => { });
}
return webpack_1.runWebpackDev().then((compiler) => {
watching = compiler.watching;
});
},
configResolved() {
if (process.env.UNI_NVUE_COMPILER === 'vue') {
return;
}
const entry = process.UNI_NVUE_ENTRY;
if (entry) {
lastNVueEntry = JSON.stringify(Object.keys(entry));
}
},
watchChange(id) {
if (process.env.UNI_NVUE_COMPILER === 'vue') {
return;
}
if (pagesJsonPath === id && watching) {
isPagesJsonChanged = true;
}
},
generateBundle() {
if (!isPagesJsonChanged) {
return;
}
const entry = process.UNI_NVUE_ENTRY;
if (!entry) {
return;
}
const curNVueEntry = JSON.stringify(Object.keys(entry));
if (curNVueEntry !== lastNVueEntry) {
lastNVueEntry = curNVueEntry;
watching.invalidate();
}
},
};
};
exports.default = [UniAppNVuePlugin()];
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./path"), exports);
__exportStar(require("./style"), exports);
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveLib = void 0;
const path_1 = __importDefault(require("path"));
function resolveLib(filepath) {
return path_1.default.resolve(__dirname, '../../lib', filepath);
}
exports.resolveLib = resolveLib;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePreprocessErrMsg = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const TIPS = `条件编译失败,参考示例(注意 ifdef 与 endif 必须配对使用):`;
const ERRORS = {
html: `${TIPS}
<!-- #ifdef %PLATFORM% -->
模板代码
<!-- #endif -->
`,
js: `${TIPS}
// #ifdef %PLATFORM%
js代码
// #endif
`,
css: `${TIPS}
/* #ifdef %PLATFORM% */
css代码
/* #endif */
`,
json: `${TIPS}
// #ifdef %PLATFORM%
json代码
// #endif
`,
};
function normalizePreprocessErrMsg(type, filepath) {
return `${ERRORS[type]} at ${uni_cli_shared_1.normalizePath(path_1.default.relative(process.env.UNI_INPUT_DIR, filepath))}:1`;
}
exports.normalizePreprocessErrMsg = normalizePreprocessErrMsg;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.genStyle = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
// @todo:
// font-relative lengths: em, ex, ch, ic
// viewport-relative lengths: vi, vb
// https://drafts.csswg.org/css-values/#lengths
const REGEXP_LENGTH = /^([-+]?[0-9]*\.?[0-9]+)(rem|vw|vh|vmin|vmax|cm|mm|q|in|pt|pc|px)$/;
function convertLength(k, v) {
if (typeof v !== 'string') {
return v;
}
const result = v.match(REGEXP_LENGTH);
if (result) {
if (result[2] === 'px') {
return result[1];
}
return result[1] + 'CSS_UNIT_' + result[2].toUpperCase();
}
return v;
}
let isFirst = true;
function genStyle(input, loader) {
let output = '{}';
const resourcePath = uni_cli_shared_1.normalizePath(path_1.default.relative(process.env.UNI_INPUT_DIR, loader.resourcePath));
require('../../lib/weex-styler').parse(input, function (err, obj) {
if (err) {
loader.emitError(err);
return;
}
if (obj && obj.jsonStyle) {
if (obj.log) {
var msgs = [];
obj.log.map((log) => {
if (log.reason.indexOf('NOTE:') !== 0) {
// 仅显示警告,错误信息
if (log.selectors) {
msgs.push(`${log.selectors}: ${log.reason} at ${resourcePath}:${log.line}`);
}
else {
msgs.push(`${log.reason} at ${resourcePath}:${log.line}`);
}
}
});
if (msgs.length) {
if (isFirst) {
msgs.unshift('nvue中不支持如下css。如全局或公共样式受影响,建议将告警样式写在ifndef APP-PLUS-NVUE的条件编译中,详情如下:');
isFirst = false;
}
msgs.forEach((msg) => console.warn(msg));
}
}
try {
output = JSON.stringify(obj.jsonStyle, convertLength, 2).replace(/"([-+]?[0-9]*\.?[0-9]+)CSS_UNIT_([A-Z]+)"/g, '$1 * CSS_UNIT.$2');
}
catch (e) { }
}
});
return output;
}
exports.genStyle = genStyle;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initModuleAlias = void 0;
const module_alias_1 = __importDefault(require("module-alias"));
const utils_1 = require("../utils");
const MODULES = [
'weex-styler',
'weex-template-compiler',
'@vue/component-compiler-utils',
'@vue/component-compiler-utils/package.json',
];
function initModuleAlias() {
MODULES.forEach((name) => module_alias_1.default.addAlias(name, utils_1.resolveLib(name)));
}
exports.initModuleAlias = initModuleAlias;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEntry = void 0;
function createEntry() {
return () => process.UNI_NVUE_ENTRY;
}
exports.createEntry = createEntry;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConfig = void 0;
const optimization_1 = require("./optimization");
const output_1 = require("./output");
const module_1 = require("./module");
const plugins_1 = require("./plugins");
const resolve_1 = require("./resolve");
const entry_1 = require("./entry");
function createConfig(mode, options) {
return {
mode: mode,
devtool: false,
watch: mode === 'development',
entry: entry_1.createEntry(),
externals: {
vue: 'Vue',
},
module: module_1.createModule(options),
optimization: optimization_1.createOptimization(),
output: output_1.createOutput(),
resolve: resolve_1.createResolve(),
plugins: plugins_1.createPlugins(),
};
}
exports.createConfig = createConfig;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createModule = void 0;
const rules_1 = require("./rules");
function createModule(options) {
return {
rules: rules_1.createRules(options),
};
}
exports.createModule = createModule;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBabelLoader = void 0;
const loader_1 = require("../../../loader");
const preprocessLoader = {
loader: loader_1.resolveLoader('preprocess'),
options: {
type: ['js'],
},
};
function createBabelLoader() {
return {
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
},
},
preprocessLoader,
],
};
}
exports.createBabelLoader = createBabelLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCssLoaders = void 0;
const oneOf_1 = require("./oneOf");
function createCssLoaders() {
return [
{
test: /\.css$/,
oneOf: oneOf_1.createOneOf(),
},
{
test: /\.scss$/,
oneOf: oneOf_1.createOneOf(scssLoader),
},
{
test: /\.sass$/,
oneOf: oneOf_1.createOneOf(sassLoader),
},
{
test: /\.less$/,
oneOf: oneOf_1.createOneOf(lessLoader),
},
{
test: /\.styl(us)?$/,
oneOf: oneOf_1.createOneOf(stylusLoader),
},
];
}
exports.createCssLoaders = createCssLoaders;
const scssLoader = {
loader: require.resolve('sass-loader'),
options: {
sourceMap: false,
additionalData: '@import "@/uni.scss";',
sassOptions: {
outputStyle: 'expanded',
},
},
};
const sassLoader = {
loader: require.resolve('sass-loader'),
options: {
sourceMap: false,
additionalData: '@import "@/uni.sass"',
sassOptions: {
outputStyle: 'expanded',
indentedSyntax: true,
},
},
};
const lessLoader = {
loader: require.resolve('less-loader'),
options: {
sourceMap: false,
},
};
const stylusLoader = {
loader: require.resolve('stylus-loader'),
options: {
sourceMap: false,
preferPathResolver: 'webpack',
},
};
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOneOf = void 0;
const path_1 = __importDefault(require("path"));
const loader_1 = require("../../../../loader");
const styleLoader = { loader: loader_1.resolveLoader('style') };
const preprocessLoader = {
loader: loader_1.resolveLoader('preprocess'),
options: {
type: ['js'],
},
};
const postcssLoader = {
loader: require.resolve('postcss-loader'),
options: {
sourceMap: false,
postcssOptions: {
parser: require('postcss-comment'),
plugins: [
require('postcss-import')({
resolve(id) {
if (id.startsWith('~@/')) {
return path_1.default.resolve(process.env.UNI_INPUT_DIR, id.substr(3));
}
else if (id.startsWith('@/')) {
return path_1.default.resolve(process.env.UNI_INPUT_DIR, id.substr(2));
}
else if (id.startsWith('/') && !id.startsWith('//')) {
return path_1.default.resolve(process.env.UNI_INPUT_DIR, id.substr(1));
}
return id;
},
}),
],
},
},
};
function createOneOf(preLoader) {
const use = [styleLoader, preprocessLoader];
use.push(postcssLoader);
if (preLoader) {
use.push(preLoader);
}
return [
{
resourceQuery: /\?vue/,
use,
},
{
use,
},
];
}
exports.createOneOf = createOneOf;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRules = void 0;
const babelLoader_1 = require("./babelLoader");
const cssLoader_1 = require("./cssLoader");
const recyclableLoader_1 = require("./recyclableLoader");
const templateLoader_1 = require("./templateLoader");
const vueLoader_1 = require("./vueLoader");
function createRules(options) {
const rules = [
vueLoader_1.createVueLoader(options),
babelLoader_1.createBabelLoader(),
recyclableLoader_1.createRecyclableLoader(),
...cssLoader_1.createCssLoaders(),
];
if (process.env.UNI_NVUE_COMPILER === 'uni-app') {
rules.push(templateLoader_1.createTemplateLoader());
}
return rules;
}
exports.createRules = createRules;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRecyclableLoader = void 0;
const loader_1 = require("../../../loader");
function createRecyclableLoader() {
return {
resourceQuery: function (query) {
return (query.indexOf('vue&type=template') !== -1 &&
query.indexOf('mpType=page') === -1);
},
use: [{ loader: loader_1.resolveLoader('recyclable') }],
};
}
exports.createRecyclableLoader = createRecyclableLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTemplateLoader = void 0;
const loader_1 = require("../../../loader");
function createTemplateLoader() {
return {
resourceQuery: function (query) {
return (query.indexOf('vue&type=template') !== -1 &&
query.indexOf('mpType=page') !== -1);
},
use: [
{ loader: loader_1.resolveLoader('scrollView') },
{
loader: loader_1.resolveLoader('pageMeta'),
},
],
};
}
exports.createTemplateLoader = createTemplateLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCompilerOptions = void 0;
const modules_1 = require("./modules");
function createCompilerOptions(options) {
return {
modules: modules_1.createModules(options),
};
}
exports.createCompilerOptions = createCompilerOptions;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAssetUrlModule = void 0;
function createAssetUrlModule() {
return {};
}
exports.createAssetUrlModule = createAssetUrlModule;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBoolAttrModule = void 0;
function createBoolAttrModule() {
return {};
}
exports.createBoolAttrModule = createBoolAttrModule;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEasycomModule = void 0;
const uni_shared_1 = require("@dcloudio/uni-shared");
const BUILT_IN_COMPONENTS = [
'App',
'block',
'component',
'transition',
'transition-group',
'keep-alive',
'slot',
'teleport',
];
function isComponent(tagName) {
if (BUILT_IN_COMPONENTS.includes(tagName)) {
return false;
}
if (uni_shared_1.isBuiltInComponent(tagName)) {
return false;
}
return true;
}
function createEasycomModule() {
return {
preTransformNode(el, options) {
if (isComponent(el.tag)) {
// 挂在 isUnaryTag 上边,可以保证外部访问到
;
(options.isUnaryTag.autoComponents ||
(options.isUnaryTag.autoComponents = new Set())).add(el.tag);
}
},
};
}
exports.createEasycomModule = createEasycomModule;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createModules = void 0;
const assetUrl_1 = require("./assetUrl");
const boolAttr_1 = require("./boolAttr");
const easycom_1 = require("./easycom");
const renderWhole_1 = require("./renderWhole");
const tags_1 = require("./tags");
function createModules(_) {
// 先处理 easycom
const modules = [easycom_1.createEasycomModule(), renderWhole_1.createRenderWholeModule()];
if (process.env.UNI_NVUE_COMPILER === 'uni-app') {
modules.push(tags_1.createTagsModule());
}
modules.push(assetUrl_1.createAssetUrlModule());
modules.push(boolAttr_1.createBoolAttrModule());
return modules;
}
exports.createModules = createModules;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRenderWholeModule = void 0;
// render-whole => append="tree"
function createRenderWholeModule() {
return {
preTransformNode(el) {
if (!Object.hasOwnProperty.call(el.attrsMap, 'append')) {
const name = 'render-whole';
const value = el.attrsMap[name];
if (value === true || value === 'true') {
// remove
delete el.attrsMap.append;
const index = el.attrsList.findIndex((item) => item.name === name);
const attr = el.attrsList[index];
el.attrsList.splice(index, 1);
el.appendAsTree = true;
el.attrsMap.append = 'tree';
el.attrsList.push({
name: 'append',
value: 'tree',
bool: false,
start: attr.start,
end: attr.end,
});
}
}
return el;
},
};
}
exports.createRenderWholeModule = createRenderWholeModule;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTagsModule = void 0;
function createTagsModule() {
return {
postTransformNode(el) {
rewriteText(el);
rewriteTag(el);
rewriteEvents(el);
rewriteVideo(el);
},
};
}
exports.createTagsModule = createTagsModule;
function rewriteText(el) {
const tag = el.tag;
if (tag === 'text' || tag === 'u-text' || tag === 'button') {
return;
}
const children = el.children;
children.forEach((child, index) => {
if (child.text) {
children.splice(index, 1, {
type: 1,
tag: 'u-text',
attrsList: [],
attrsMap: {},
rawAttrsMap: {},
parent: el,
children: [child],
plain: true,
});
}
});
}
const TAGS = [
'text',
'image',
'input',
'textarea',
'video',
'web-view',
// 'switch',
'slider',
];
function rewriteTag(el) {
if (TAGS.includes(el.tag)) {
el.tag = 'u-' + el.tag;
}
else if (el.tag === 'match-media') {
el.tag = 'uni-match-media';
}
}
const deprecated = {
events: {
tap: 'click',
},
};
function rewriteEvents(el) {
if (!el.events) {
return;
}
const { events: eventsMap } = deprecated;
Object.keys(el.events).forEach((name) => {
// 过时事件类型转换
const eventType = eventsMap[name];
if (eventType) {
if (!(name === 'tap' && el.tag === 'map')) {
// map 的 tap 事件不做转换
el.events[eventType] = el.events[name];
delete el.events[name];
}
}
});
}
function rewriteVideo(el) {
if (el.tag !== 'u-video') {
return;
}
if (!Array.isArray(el.children)) {
return;
}
if (!el.children.length) {
return;
}
if (el.children[0].tag === 'u-scalable') {
return;
}
el.children = [
{
type: 1,
tag: 'u-scalable',
attrsList: [],
attrsMap: {
style: 'position: absolute;left: 0;right: 0;top: 0;bottom: 0;',
},
rawAttrsMap: {
style: {
name: 'style',
value: 'position: absolute;left: 0;right: 0;top: 0;bottom: 0;',
},
},
parent: el,
plain: false,
staticStyle: '{position:"absolute",left:"0",right:"0",top:"0",bottom:"0"}',
children: el.children,
},
];
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateEasycomCode = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function generateEasycomCode(names) {
const components = [];
resolveEasycom(names).forEach(({ name, source }) => {
// 统一转换为驼峰命名
name = name.replace(/-(\w)/g, (_, str) => str.toUpperCase());
components.push(`'${name}': require('${source}').default`);
});
if (process.env.NODE_ENV === 'production') {
return `var components = {${components.join(',')}}`;
}
return `var components;
try{
components = {${components.join(',')}}
}catch(e){
if(e.message.indexOf('Cannot find module') !== -1 && e.message.indexOf('.vue') !== -1){
console.error(e.message)
console.error('1. 排查组件名称拼写是否正确')
console.error('2. 排查组件是否符合 easycom 规范,文档:https://uniapp.dcloud.net.cn/collocation/pages?id=easycom')
console.error('3. 若组件不符合 easycom 规范,需手动引入,并在 components 中注册该组件')
} else {
throw e
}
}`;
}
exports.generateEasycomCode = generateEasycomCode;
function resolveEasycom(names) {
return names.reduce((coms, name) => {
const source = uni_cli_shared_1.matchEasycom(name);
if (source) {
coms.push({
name,
source,
});
}
return coms;
}, []);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createVueLoader = void 0;
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const compilerOptions_1 = require("./compilerOptions");
const utils_1 = require("../../../../../utils");
const easycom_1 = require("./easycom");
const loader_1 = require("../../../../loader");
const preprocessLoader = {
loader: loader_1.resolveLoader('preprocess'),
options: {
type: ['js', 'html'],
},
};
function createVueLoader(options) {
uni_cli_shared_1.initEasycomsOnce(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
return {
test: [/\.nvue(\?[^?]+)?$/, /\.vue(\?[^?]+)?$/],
use: [
{
loader: utils_1.resolveLib('vue-loader'),
options: {
hotReload: false,
compiler: createCompiler(),
compilerOptions: compilerOptions_1.createCompilerOptions(options),
},
},
preprocessLoader,
],
};
}
exports.createVueLoader = createVueLoader;
const isUnaryTag = shared_1.makeMap('image,area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr');
function compileTemplate(source, options, compile) {
const res = compile(source, options);
res.components = easycom_1.generateEasycomCode([
...(options.isUnaryTag.autoComponents || []),
]);
return res;
}
function createCompiler() {
const compiler = require(utils_1.resolveLib('weex-template-compiler'));
const oldCompile = compiler.compile;
compiler.compile = function (source, options = {}) {
;
options.isUnaryTag = isUnaryTag;
options.isUnaryTag.autoComponents = new Set();
options.preserveWhitespace = false;
return compileTemplate(source, options, oldCompile);
};
return compiler;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOptimization = void 0;
const terser_webpack_plugin_1 = __importDefault(require("terser-webpack-plugin"));
function createOptimization() {
return {
nodeEnv: false,
moduleIds: 'deterministic',
chunkIds: 'deterministic',
minimizer: [
new terser_webpack_plugin_1.default({
terserOptions: {
output: {
ascii_only: true,
},
},
}),
],
};
}
exports.createOptimization = createOptimization;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOutput = void 0;
function createOutput() {
return {
path: process.env.UNI_OUTPUT_DIR,
filename: '[name].js',
};
}
exports.createOutput = createOutput;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBannerPlugin = void 0;
const BannerPlugin_1 = __importDefault(require("../../plugin/BannerPlugin"));
function createBannerPlugin() {
return new BannerPlugin_1.default({
banner: '"use weex:vue";',
});
}
exports.createBannerPlugin = createBannerPlugin;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDefinePlugin = void 0;
const webpack_1 = require("webpack");
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function createDefinePlugin() {
return new webpack_1.DefinePlugin(shared_1.extend({
'process.env.UNI_CLOUD_PROVIDER': process.env.UNI_CLOUD_PROVIDER,
'process.env.HBX_USER_TOKEN': JSON.stringify(process.env.HBX_USER_TOKEN || ''),
}, uni_cli_shared_1.initDefine()));
}
exports.createDefinePlugin = createDefinePlugin;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPlugins = void 0;
const define_1 = require("./define");
const banner_1 = require("./banner");
const provide_1 = require("./provide");
const vueLoader_1 = require("./vueLoader");
function createPlugins() {
return [
define_1.createDefinePlugin(),
banner_1.createBannerPlugin(),
provide_1.createProvidePlugin(),
vueLoader_1.createVueLoaderPlugin(),
];
}
exports.createPlugins = createPlugins;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createProvidePlugin = void 0;
const webpack_1 = require("webpack");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../../utils");
function createProvidePlugin() {
return new webpack_1.ProvidePlugin({
uniCloud: [
require.resolve('@dcloudio/uni-cloud/dist/uni-cloud.es.js'),
'default',
],
'uni.getCurrentSubNVue': [utils_1.resolveLib('get-current-sub-nvue.js'), 'default'],
'uni.requireNativePlugin': [
utils_1.resolveLib('require-native-plugin.js'),
'default',
],
...uni_cli_shared_1.initProvide(),
});
}
exports.createProvidePlugin = createProvidePlugin;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createVueLoaderPlugin = void 0;
function createVueLoaderPlugin() {
const { VueLoaderPlugin } = require('../../../../lib/vue-loader');
return new VueLoaderPlugin();
}
exports.createVueLoaderPlugin = createVueLoaderPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createResolve = void 0;
const path_1 = __importDefault(require("path"));
// import { resolveMainPathOnce } from '@dcloudio/uni-cli-shared'
function createResolve() {
const inputDir = process.env.UNI_INPUT_DIR;
return {
extensions: ['.js', '.nvue', '.vue', '.json'],
alias: {
'@': inputDir,
// '@dcloudio/uni-stat': require.resolve('@dcloudio/uni-stat')
// 'uni-app-style':
// resolveMainPathOnce(inputDir) +
// '?' +
// JSON.stringify({
// type: 'appStyle'
// })
},
modules: [
'node_modules',
path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'node_modules'),
path_1.default.resolve(inputDir, 'node_modules'),
],
};
}
exports.createResolve = createResolve;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runWebpackDev = exports.runWebpackBuild = void 0;
const webpack_1 = __importDefault(require("webpack"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const config_1 = require("./config");
const alias_1 = require("./alias");
const initModuleAliasOnce = uni_shared_1.once(alias_1.initModuleAlias);
function runWebpack(mode, options) {
initModuleAliasOnce();
return new Promise((resolve, reject) => {
const compiler = webpack_1.default(config_1.createConfig(mode, options), (err, stats) => {
if (err) {
return reject(err.stack || err);
}
if (stats.hasErrors()) {
return reject(stats.toString());
}
if (stats.hasWarnings()) {
const info = stats.toJson({ all: false, warnings: true });
console.warn(info.warnings);
}
if (process.env.DEBUG) {
console.log(stats.toString({
all: false,
assets: true,
colors: true, // 在控制台展示颜色
// timings: true,
}));
}
resolve(compiler);
});
});
}
function runWebpackBuild(options = {}) {
return runWebpack('production', options);
}
exports.runWebpackBuild = runWebpackBuild;
function runWebpackDev(options = {}) {
return runWebpack('development', options);
}
exports.runWebpackDev = runWebpackDev;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveLoader = void 0;
const path_1 = __importDefault(require("path"));
function resolveLoader(loader) {
return path_1.default.resolve(__dirname, loader);
}
exports.resolveLoader = resolveLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function pageLoader(content) { }
exports.default = pageLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function pageMetaLoader(content, map) {
// 简单判断,只要包含 page-meta,就在外层包裹一层 view (vue2 不支持多 root)
if (content.indexOf('<page-meta') !== -1) {
return this.callback(null, `<view>${content}</view>`, map);
}
this.callback(null, content, map);
}
exports.default = pageMetaLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const preprocess_1 = require("../../utils/preprocess");
const utils = require('loader-utils');
function preprocessLoader(content, map) {
if (content.indexOf('#ifdef') === -1) {
return this.callback(null, content, map);
}
const types = utils.getOptions(this)
.type || ['js'];
const resourcePath = this.resourcePath;
types.forEach((type) => {
try {
content = preContent(type, content);
}
catch (e) {
console.error(preprocess_1.normalizePreprocessErrMsg(type, resourcePath));
}
});
this.callback(null, content, map);
}
function preContent(type, content) {
switch (type) {
case 'js':
return uni_cli_shared_1.preNVueJs(content);
case 'html':
return uni_cli_shared_1.preNVueHtml(content);
case 'css':
return uni_cli_shared_1.preNVueCss(content);
case 'json':
return uni_cli_shared_1.preNVueJson(content);
}
return content;
}
exports.default = preprocessLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const loaderUtils = require('loader-utils');
function recyclableLoader(content, map) {
const vueLoaderOptions = this.loaders.find((loader) => loader.ident === 'vue-loader-options');
if (vueLoaderOptions) {
const params = loaderUtils.parseQuery(this.resourceQuery);
if (params.recyclable) {
;
vueLoaderOptions.options.compilerOptions.recyclable = true;
}
}
else {
throw new Error('vue-loader-options parse error');
}
this.callback(null, content, map);
}
exports.default = recyclableLoader;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const SCROLLER_COMPONENTS = ['list', 'scroller', 'scroll-view', 'waterfall'];
function scrollViewLoader(content, map) {
const source = content.trim();
if (SCROLLER_COMPONENTS.find((name) => source.indexOf('<' + name) === 0)) {
return this.callback(null, content, map);
}
if (source.indexOf('<recycle-list') !== -1) {
return this.callback(null, content, map);
}
let resourcePath = uni_cli_shared_1.removeExt(uni_cli_shared_1.normalizePath(path_1.default.relative(process.env.UNI_INPUT_DIR, this.resourcePath)));
if (!process.UNI_NVUE_ENTRY[resourcePath] &&
this._module.issuer &&
this._module.issuer.issuer) {
// <template src=""/>
resourcePath = uni_cli_shared_1.removeExt(uni_cli_shared_1.normalizePath(path_1.default.relative(process.env.UNI_INPUT_DIR, this._module.issuer.issuer.resource)));
}
// 是否 disableScroll
// TODO 暂时仅读取一次配置,开发者实时修改页面配置,不会实时生效
const pagesJson = uni_cli_shared_1.parsePagesJsonOnce(process.env.UNI_INPUT_DIR, 'app');
const pageJson = pagesJson.pages.find((page) => page.path === resourcePath);
if (!pageJson) {
return this.callback(null, content, map);
}
if (pageJson.style.disableScroll) {
return this.callback(null, content, map);
}
this.callback(null, `<scroll-view :scroll-y="true" :show-scrollbar="${pageJson.style.scrollIndicator === 'none' ? 'false' : 'true'}" :enableBackToTop="true" bubble="true" style="flex-direction:column">${content}</scroll-view>`, map);
}
exports.default = scrollViewLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("../../utils");
function styleLoader(content, map) {
this.callback(null, 'module.exports = ' + utils_1.genStyle(content, this), map);
}
exports.default = styleLoader;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const webpack_1 = require("webpack");
const webpack_sources_1 = require("webpack-sources");
class BannerPlugin {
/**
* @param {BannerPluginArgument} options options object
*/
constructor(options) {
this.banner = () => options.banner;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const banner = this.banner;
compiler.hooks.compilation.tap('BannerPlugin', (compilation) => {
compilation.hooks.processAssets.tap({
name: 'BannerPlugin',
stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER,
}, () => {
for (const chunk of compilation.chunks) {
if (!chunk.canBeInitial()) {
continue;
}
for (const file of chunk.files) {
const data = {
chunk,
filename: file,
};
const comment = compilation.getPath(banner, data);
compilation.updateAsset(file, (old) => new webpack_sources_1.ConcatSource(comment, '\n', old));
}
}
});
});
}
}
exports.default = BannerPlugin;
......@@ -3,6 +3,7 @@ import { createDefinePlugin } from './define'
import { createBannerPlugin } from './banner'
import { createProvidePlugin } from './provide'
import { createVueLoaderPlugin } from './vueLoader'
import WatchPlugin from '../../plugin/WatchPlugin'
export function createPlugins(): Configuration['plugins'] {
return [
......@@ -10,5 +11,6 @@ export function createPlugins(): Configuration['plugins'] {
createBannerPlugin(),
createProvidePlugin(),
createVueLoaderPlugin(),
new WatchPlugin(),
]
}
import { Compiler } from 'webpack'
import { M } from '@dcloudio/uni-cli-shared'
export default class WatchPlugin {
constructor() {}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler: Compiler) {
const chunkVersions: Record<string, string> = {}
let isFirst = true
let isCompiling = false
compiler.hooks.invalid.tap('WatchPlugin', () => {
if (!isCompiling) {
isCompiling = true
console.log(M['dev.watching.start'])
}
})
compiler.hooks.done.tap('WatchPlugin', (stats) => {
isCompiling = false
if (isFirst) {
return (isFirst = false)
}
const changedFiles: Set<string> = new Set<string>()
stats.compilation.chunks.forEach(({ name, hash, files }) => {
if (!hash) {
return
}
const oldVersion = chunkVersions[name]
chunkVersions[name] = hash
if (hash === oldVersion) {
return
}
files.forEach((file) => changedFiles.add(file))
})
if (changedFiles.size) {
console.log(
M['dev.watching.end.pages'].replace(
'{pages}',
JSON.stringify([...changedFiles])
)
)
} else {
console.log(M['dev.watching.end'])
}
})
}
}
......@@ -25,7 +25,3 @@ export const COMMON_EXCLUDE = [
/\/@dcloudio\/uni-h5\/style/,
/\/@dcloudio\/uni-components\/style/,
]
export const TIPS_BUILD_COMPLETE = 'DONE Build complete.'
export const TIPS_WATCH_FOR_CHANGES =
TIPS_BUILD_COMPLETE + ' Watching for changes...'
......@@ -13,5 +13,6 @@ export * from './preprocess'
export * from './postcss'
export * from './renderjs'
export * from './esbuild'
export { M } from './messages'
export { checkUpdate } from './checkUpdate'
export const M = {
'app.compiler.version': '编译器版本:{version}',
'dev.performance':
'请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。',
'dev.performance.nvue': '尤其是app-nvue的sourcemap影响较大',
'dev.performance.mp': '若要正式发布,请点击发行菜单或使用cli发布命令进行发布',
'build.done': 'DONE Build complete.',
'dev.watching.start': '开始差量编译...',
'dev.watching.end': 'DONE Build complete. Watching for changes...',
'dev.watching.end.pages': 'DONE Build complete. PAGES:{pages}',
'dev.watching.end.files': 'DONE Build complete. FILES:{files}',
}
import { Plugin, ResolvedConfig } from 'vite'
import { FileWatcher } from '../../watcher'
import { TIPS_WATCH_FOR_CHANGES } from '../../constants'
import { M } from '../../messages'
export interface UniViteCopyPluginTarget {
src: string | string[]
dest: string
......@@ -48,7 +48,7 @@ export function uniViteCopyPlugin({
}
},
() => {
console.log(TIPS_WATCH_FOR_CHANGES)
console.log(M['dev.watching.end'])
}
)
})
......
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const plugin_1 = require("./plugin");
const css_1 = require("./plugins/css");
const inject_1 = require("./plugins/inject");
const mainJs_1 = require("./plugins/mainJs");
const manifestJson_1 = require("./plugins/manifestJson");
const pagesJson_1 = require("./plugins/pagesJson");
const renderjs_1 = require("./plugins/renderjs");
const resolveId_1 = require("./plugins/resolveId");
const setup_1 = require("./plugins/setup");
const ssr_1 = require("./plugins/ssr");
exports.default = [
uni_cli_shared_1.uniCssScopedPlugin(),
resolveId_1.uniResolveIdPlugin(),
mainJs_1.uniMainJsPlugin(),
manifestJson_1.uniManifestJsonPlugin(),
pagesJson_1.uniPagesJsonPlugin(),
inject_1.uniInjectPlugin(),
css_1.uniCssPlugin(),
ssr_1.uniSSRPlugin(),
setup_1.uniSetupPlugin(),
renderjs_1.uniRenderjsPlugin(),
plugin_1.UniH5Plugin,
];
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHandleHotUpdate = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../utils");
const debugHmr = debug_1.default('vite:uni:hmr');
async function invalidate(file, moduleGraph) {
const mods = await moduleGraph.getModulesByFile(uni_cli_shared_1.normalizePath(file));
if (mods && mods.size) {
;
[...mods].forEach((mod) => {
debugHmr('invalidate', mod.id);
moduleGraph.invalidateModule(mod);
});
}
}
let invalidateFiles;
function createHandleHotUpdate() {
return async function ({ file, server }) {
const inputDir = process.env.UNI_INPUT_DIR;
const platform = process.env.UNI_PLATFORM;
if (!invalidateFiles) {
invalidateFiles = [
path_1.default.resolve(inputDir, 'pages.json.js'),
path_1.default.resolve(inputDir, 'manifest.json.js'),
require.resolve('@dcloudio/uni-h5/dist/uni-h5.es.js'),
];
try {
invalidateFiles.push(require.resolve('vite/dist/client/env.mjs'));
}
catch (e) { }
}
// TODO 目前简单处理,当pages.json,manifest.json发生变化,就直接刷新,理想情况下,应该区分变化的内容,仅必要时做整页面刷新
const isPagesJson = file.endsWith('pages.json');
const isManifestJson = file.endsWith('manifest.json');
if (!isPagesJson && !isManifestJson) {
return;
}
debugHmr(file);
const pagesJson = uni_cli_shared_1.parsePagesJson(inputDir, platform);
// 更新define
const { define, server: { middlewareMode }, } = server.config;
shared_1.extend(define, utils_1.initFeatures({
inputDir,
command: 'serve',
platform,
pagesJson,
manifestJson: uni_cli_shared_1.parseManifestJson(inputDir),
ssr: !!middlewareMode,
}));
debugHmr('define', define);
if (isPagesJson) {
const easycom = pagesJson.easycom || {};
const { options, refresh } = uni_cli_shared_1.initEasycomsOnce(inputDir, platform);
if (!equal({ autoscan: easycom.autoscan, custom: easycom.custom }, { autoscan: options.autoscan, custom: options.custom })) {
refresh();
}
}
// 当pages.json,manifest.json发生变化时,作废pages.json.js缓存
for (const file of invalidateFiles) {
await invalidate(file, server.moduleGraph);
}
server.ws.send({
type: 'full-reload',
path: '*',
});
return [];
};
}
exports.createHandleHotUpdate = createHandleHotUpdate;
function equal(obj1, obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UniH5Plugin = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const handleHotUpdate_1 = require("./handleHotUpdate");
const transformIndexHtml_1 = require("./transformIndexHtml");
const features_1 = require("../utils/features");
exports.UniH5Plugin = {
name: 'vite:uni-h5',
uni: {
copyOptions: {
assets: ['hybrid/html'],
},
transformEvent: {
tap: 'click',
},
},
config(config, env) {
if (uni_cli_shared_1.isInHBuilderX()) {
if (!fs_1.default.existsSync(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'index.html'))) {
console.error(`请确认您的项目模板是否支持vue3:根目录缺少 index.html`);
process.exit();
}
}
return {
optimizeDeps: {
exclude: ['@dcloudio/uni-h5', '@dcloudio/uni-h5-vue'],
},
define: features_1.createDefine(env.command, config),
};
},
configResolved(config) {
// TODO 禁止 optimizeDeps
;
config.cacheDir = '';
},
handleHotUpdate: handleHotUpdate_1.createHandleHotUpdate(),
transformIndexHtml: transformIndexHtml_1.createTransformIndexHtml(),
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTransformIndexHtml = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function createTransformIndexHtml() {
return async function (html) {
var _a;
const manifestJson = uni_cli_shared_1.parseManifestJsonOnce(process.env.UNI_INPUT_DIR);
const title = ((_a = manifestJson.h5) === null || _a === void 0 ? void 0 : _a.title) || manifestJson.name || '';
return html.replace(/<title>(.*?)<\/title>/, `<title>${title}</title>`);
};
}
exports.createTransformIndexHtml = createTransformIndexHtml;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniCssPlugin = void 0;
const fs_1 = __importDefault(require("fs"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function isCombineBuiltInCss(config) {
return config.command === 'build' && config.build.cssCodeSplit;
}
function uniCssPlugin() {
let resolvedConfig;
return {
name: 'vite:uni-h5-css',
apply: 'build',
enforce: 'post',
configResolved(config) {
resolvedConfig = config;
},
generateBundle(_opts, bundle) {
// 将内置组件样式,合并进入首页
if (!isCombineBuiltInCss(resolvedConfig) || !uni_cli_shared_1.buildInCssSet.size) {
return;
}
const chunks = Object.values(bundle);
const entryChunk = chunks.find((chunk) => chunk.type === 'chunk' && chunk.isEntry);
if (!entryChunk) {
return;
}
const entryName = entryChunk.name;
const entryCssAsset = chunks.find(({ name }) => name === entryName + '.css');
if (entryCssAsset) {
entryCssAsset.source =
generateBuiltInCssCode([...uni_cli_shared_1.buildInCssSet]) +
'\n' +
entryCssAsset.source;
}
},
};
}
exports.uniCssPlugin = uniCssPlugin;
function generateBuiltInCssCode(cssImports) {
return cssImports
.map((cssImport) => fs_1.default.readFileSync(uni_cli_shared_1.resolveBuiltIn(cssImport), 'utf8'))
.join('\n');
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniInjectPlugin = void 0;
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const apiJson = require(path_1.default.resolve(__dirname, '../../lib/api.json'));
const uniInjectPluginOptions = {
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE],
'uni.': [
'@dcloudio/uni-h5',
((method) => apiJson.includes(method)),
],
getApp: ['@dcloudio/uni-h5', 'getApp'],
getCurrentPages: ['@dcloudio/uni-h5', 'getCurrentPages'],
UniServiceJSBridge: ['@dcloudio/uni-h5', 'UniServiceJSBridge'],
UniViewJSBridge: ['@dcloudio/uni-h5', 'UniViewJSBridge'],
};
function uniInjectPlugin() {
let resolvedConfig;
const callback = function (imports, mod) {
const styles = mod[0] === '@dcloudio/uni-h5' &&
uni_cli_shared_1.API_DEPS_CSS[mod[1]];
if (!styles) {
return;
}
styles.forEach((style) => {
if (uni_cli_shared_1.isCombineBuiltInCss(resolvedConfig)) {
uni_cli_shared_1.buildInCssSet.add(style);
}
else {
if (!imports.has(style)) {
imports.set(style, `import '${style}';`);
}
}
});
};
const injectPlugin = uni_cli_shared_1.uniViteInjectPlugin(shared_1.extend(uniInjectPluginOptions, {
callback,
}));
return {
name: 'vite:uni-h5-inject',
apply: 'build',
enforce: 'post',
configResolved(config) {
resolvedConfig = config;
},
transform(code, id) {
return injectPlugin.transform.call(this, code, id);
},
};
}
exports.uniInjectPlugin = uniInjectPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMainJsPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
function uniMainJsPlugin() {
return uni_cli_shared_1.defineUniMainJsPlugin((opts) => {
let pagesJsonJsPath = '';
let isSSR = false;
return {
name: 'vite:uni-h5-main-js',
enforce: 'pre',
configResolved(config) {
pagesJsonJsPath = uni_cli_shared_1.normalizePath(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json.js'));
isSSR =
utils_1.isSsr(config.command, config) || utils_1.isSsrManifest(config.command, config);
},
transform(code, id, ssr) {
if (opts.filter(id)) {
if (!isSSR) {
code = code.includes('createSSRApp')
? createApp(code)
: createLegacyApp(code);
}
else {
code = ssr ? createSSRServerApp(code) : createSSRClientApp(code);
}
code = `import '${pagesJsonJsPath}';${code}`;
return {
code,
map: this.getCombinedSourcemap(),
};
}
},
};
});
}
exports.uniMainJsPlugin = uniMainJsPlugin;
function createApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';createApp().app.use(__plugin).mount("#app");${code.replace('createSSRApp', 'createVueApp as createSSRApp')}`;
}
function createLegacyApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps).use(__plugin)};${code.replace('createApp', 'createVueApp')}`;
}
function createSSRClientApp(code) {
return `import { plugin as __plugin } from '@dcloudio/uni-h5';import { UNI_SSR, UNI_SSR_STORE } from '@dcloudio/uni-shared';const { app: __app, store: __store } = createApp();__app.use(__plugin);__store && window[UNI_SSR] && window[UNI_SSR][UNI_SSR_STORE] && __store.replaceState(window[UNI_SSR][UNI_SSR_STORE]);__app.router.isReady().then(() => __app.mount("#app"));${code}`;
}
function createSSRServerApp(code) {
return code;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniManifestJsonPlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const defaultRouter = {
mode: 'hash',
base: '/',
};
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 60000,
suspensible: true,
};
const defaultQQMapKey = 'XVXBZ-NDMC4-JOGUS-XGIEE-QVHDZ-AMFV2';
function uniManifestJsonPlugin() {
return uni_cli_shared_1.defineUniManifestJsonPlugin((opts) => {
return {
name: 'vite:uni-h5-manifest-json',
enforce: 'pre',
transform(code, id) {
if (!opts.filter(id)) {
return;
}
const manifest = uni_cli_shared_1.parseJson(code);
const { debug, h5 } = manifest;
const appid = (manifest.appid || '').replace('__UNI__', '');
const router = { ...defaultRouter, ...((h5 && h5.router) || {}) };
if (!router.base) {
router.base = '/';
}
const async = { ...defaultAsync, ...((h5 && h5.async) || {}) };
const networkTimeout = uni_cli_shared_1.normalizeNetworkTimeout(manifest.networkTimeout);
const sdkConfigs = (h5 && h5.sdkConfigs) || {};
const qqMapKey = (sdkConfigs.maps &&
sdkConfigs.maps.qqmap &&
sdkConfigs.maps.qqmap.key) ||
defaultQQMapKey;
const flexDirection = (manifest['app'] &&
manifest['app'].nvue &&
manifest['app'].nvue['flex-direction']) ||
'column';
return {
code: `export const appid = '${appid || ''}'
export const debug = ${!!debug}
export const nvue = ${JSON.stringify({
'flex-direction': flexDirection,
})}
export const networkTimeout = ${JSON.stringify(networkTimeout)}
// h5
export const router = ${JSON.stringify(router)}
export const async = ${JSON.stringify(async)}
export const qqMapKey = '${qqMapKey}'
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
`,
map: { mappings: '' },
};
},
};
});
}
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPagesJsonPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const pkg = require('@dcloudio/vite-plugin-uni/package.json');
function uniPagesJsonPlugin() {
return uni_cli_shared_1.defineUniPagesJsonPlugin((opts) => {
return {
name: 'vite:uni-h5-pages-json',
enforce: 'pre',
transform(code, id, ssr) {
if (opts.filter(id)) {
const { resolvedConfig } = opts;
return {
code: registerGlobalCode(resolvedConfig, ssr) +
generatePagesJsonCode(ssr, code, resolvedConfig),
map: { mappings: '' },
};
}
},
};
});
}
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
function generatePagesJsonCode(ssr, jsonStr, config) {
const globalName = getGlobal(ssr);
const pagesJson = uni_cli_shared_1.normalizePagesJson(jsonStr, process.env.UNI_PLATFORM);
const { importLayoutComponentsCode, defineLayoutComponentsCode } = generateLayoutComponentsCode(globalName, pagesJson);
const definePagesCode = generatePagesDefineCode(pagesJson, config);
const uniRoutesCode = generateRoutes(globalName, pagesJson, config);
const uniConfigCode = generateConfig(globalName, pagesJson, config);
const manifestJsonPath = uni_cli_shared_1.normalizePath(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'manifest.json.js'));
const cssCode = generateCssCode(config);
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent, setupWindow } from '@dcloudio/uni-h5'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue } from '${manifestJsonPath}'
${importLayoutComponentsCode}
const extend = Object.assign
${cssCode}
${uniConfigCode}
${defineLayoutComponentsCode}
${definePagesCode}
${uniRoutesCode}
${config.command === 'serve' ? hmrCode : ''}
export {}
`;
}
const hmrCode = `if(import.meta.hot){
import.meta.hot.on('invalidate', (data) => {
import.meta.hot.invalidate()
})
}`;
function getGlobal(ssr) {
return ssr ? 'global' : 'window';
}
function registerGlobalCode(config, ssr) {
const name = getGlobal(ssr);
if (config.command === 'build' && !ssr) {
// 非SSR的发行模式,补充全局 uni 对象
return `${name}.uni = {}`;
}
const rpx2pxCode = !ssr && config.define.__UNI_FEATURE_RPX__
? `import {upx2px} from '@dcloudio/uni-h5'
${name}.rpx2px = upx2px
`
: '';
return `${rpx2pxCode}
import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5'
${name}.getApp = getApp
${name}.getCurrentPages = getCurrentPages
${name}.uni = uni
${name}.UniViewJSBridge = UniViewJSBridge
${name}.UniServiceJSBridge = UniServiceJSBridge
`;
}
function generateCssCode(config) {
const define = config.define;
const cssFiles = [uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'base.css'];
// if (define.__UNI_FEATURE_PAGES__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'async.css');
// }
if (define.__UNI_FEATURE_RESPONSIVE__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'layout.css');
}
if (define.__UNI_FEATURE_NAVIGATIONBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageHead.css');
}
if (define.__UNI_FEATURE_TABBAR__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'tabBar.css');
}
if (define.__UNI_FEATURE_NVUE__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'nvue.css');
}
if (define.__UNI_FEATURE_PULL_DOWN_REFRESH__) {
cssFiles.push(uni_cli_shared_1.H5_FRAMEWORK_STYLE_PATH + 'pageRefresh.css');
}
if (define.__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__) {
cssFiles.push(uni_cli_shared_1.BASE_COMPONENTS_STYLE_PATH + 'input.css');
}
if (config.command === 'serve') {
// 开发模式,自动添加所有API相关css
Object.keys(uni_cli_shared_1.API_DEPS_CSS).forEach((name) => {
const styles = uni_cli_shared_1.API_DEPS_CSS[name];
styles.forEach((style) => {
if (!cssFiles.includes(style)) {
cssFiles.push(style);
}
});
});
}
return cssFiles.map((file) => `import '${file}'`).join('\n');
}
function generateLayoutComponentsCode(globalName, pagesJson) {
const windowNames = {
topWindow: -1,
leftWindow: -2,
rightWindow: -3,
};
let importLayoutComponentsCode = '';
let defineLayoutComponentsCode = `${globalName}.__uniLayout = ${globalName}.__uniLayout || {}\n`;
Object.keys(windowNames).forEach((name) => {
const windowConfig = pagesJson[name];
if (windowConfig && windowConfig.path) {
importLayoutComponentsCode += `import ${name} from './${windowConfig.path}'\n`;
defineLayoutComponentsCode += `${globalName}.__uniConfig.${name}.component = setupWindow(${name},${windowNames[name]})\n`;
}
});
return {
importLayoutComponentsCode,
defineLayoutComponentsCode,
};
}
function generatePageDefineCode(pageOptions) {
let pagePathWithExtname = uni_cli_shared_1.normalizePagePath(pageOptions.path, 'h5');
if (!pagePathWithExtname) {
// 不存在时,仍引用,此时编译会报错文件不存在
pagePathWithExtname = pageOptions.path + '.vue';
}
const pageIdent = uni_cli_shared_1.normalizeIdentifier(pageOptions.path);
return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}?mpType=page')
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`;
}
function generatePagesDefineCode(pagesJson, _config) {
const { pages } = pagesJson;
return (`const AsyncComponentOptions = {
loadingComponent: AsyncLoadingComponent,
errorComponent: AsyncErrorComponent,
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
}
` + pages.map((pageOptions) => generatePageDefineCode(pageOptions)).join('\n'));
}
function generatePageRoute({ path, meta }, _config) {
const { isEntry } = meta;
const alias = isEntry ? `\n alias:'/${path}',` : '';
return `{
path:'/${isEntry ? '' : path}',${alias}
component:{setup(){return ()=>renderPage(${uni_cli_shared_1.normalizeIdentifier(path)})}},
loader: ${uni_cli_shared_1.normalizeIdentifier(path)}Loader,
meta: ${JSON.stringify(meta)}
}`;
}
function generatePagesRoute(pagesRouteOptions, config) {
return pagesRouteOptions.map((pageOptions) => generatePageRoute(pageOptions, config));
}
function generateRoutes(globalName, pagesJson, config) {
return `
function renderPage(component){
return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, { ref: "page" }, null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */}))
}
${globalName}.__uniRoutes=[${[
...generatePagesRoute(uni_cli_shared_1.normalizePagesRoute(pagesJson), config),
].join(',')}].map(uniRoute=>(uniRoute.meta.route = (uniRoute.alias || uniRoute.path).substr(1),uniRoute))`;
}
function generateConfig(globalName, pagesJson, config) {
delete pagesJson.pages;
delete pagesJson.subPackages;
delete pagesJson.subpackages;
pagesJson.compilerVersion = pkg['uni-app'].compilerVersion;
return ((config.command === 'serve'
? ''
: `${globalName}['____'+appid+'____']=true
delete ${globalName}['____'+appid+'____']
`) +
`${globalName}.__uniConfig=extend(${JSON.stringify(pagesJson)},{
async,
debug,
networkTimeout,
sdkConfigs,
qqMapKey,
nvue,
router
})
`);
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniRenderjsPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const compiler_sfc_1 = require("@vue/compiler-sfc");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugRenderjs = debug_1.default('vite:uni:renderjs');
function uniRenderjsPlugin() {
return {
name: 'vite:uni-h5-renderjs',
transform(code, id) {
const { type, name } = uni_cli_shared_1.parseRenderjs(id);
if (!type) {
return;
}
debugRenderjs(id);
if (!name) {
this.error(uni_cli_shared_1.missingModuleName(type, code));
}
return `${compiler_sfc_1.rewriteDefault(code.replace(/module\.exports\s*=/, 'export default '), '_sfc_' + type)}
${type === 'renderjs' ? genRenderjsCode(name) : genWxsCode(name)}`;
},
};
}
exports.uniRenderjsPlugin = uniRenderjsPlugin;
function genRenderjsCode(name) {
return `export default Comp => {
if(!Comp.$renderjs){Comp.$renderjs = []}
Comp.$renderjs.push('${name}')
if(!Comp.mixins){Comp.mixins = []}
Comp.mixins.push({beforeCreate(){ this['${name}'] = this }})
Comp.mixins.push(_sfc_renderjs)
}`;
}
function genWxsCode(name) {
return `export default Comp => {
if(!Comp.$wxs){Comp.$wxs = []}
Comp.$wxs.push('${name}')
if(!Comp.mixins){Comp.mixins = []}
Comp.mixins.push({beforeCreate(){ this['${name}'] = _sfc_wxs }})
}`;
}
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniResolveIdPlugin = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugResolve = debug_1.default('vite:uni:resolve');
function uniResolveIdPlugin() {
const resolveCache = {};
return {
name: 'vite:uni-h5-resolve-id',
enforce: 'pre',
configResolved() {
const { MODE } = uni_cli_shared_1.parseCompatConfigOnce(process.env.UNI_INPUT_DIR);
resolveCache['@dcloudio/uni-h5'] = uni_cli_shared_1.resolveBuiltIn(path_1.default.join('@dcloudio/uni-h5', 'dist/uni-h5.es.js'));
resolveCache['@dcloudio/uni-h5-vue'] = uni_cli_shared_1.resolveBuiltIn(path_1.default.join('@dcloudio/uni-h5-vue', `dist/vue.runtime.${MODE === 2 ? 'compat.' : ''}esm.js`));
},
resolveId(id) {
if (id === 'vue') {
id = '@dcloudio/uni-h5-vue';
}
const cache = resolveCache[id];
if (cache) {
debugResolve('cache', id, cache);
return cache;
}
if (id.startsWith('@dcloudio/uni-h5/style') ||
id.startsWith('@dcloudio/uni-components/style')) {
return (resolveCache[id] = uni_cli_shared_1.resolveBuiltIn(id));
}
},
};
}
exports.uniResolveIdPlugin = uniResolveIdPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSetupPlugin = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugSetup = debug_1.default('vite:uni:setup');
function uniSetupPlugin() {
let appVuePath;
return {
name: 'vite:uni-setup',
configResolved() {
appVuePath = uni_cli_shared_1.normalizePath(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'App.vue'));
},
transform(code, id) {
const { filename, query } = uni_cli_shared_1.parseVueRequest(id);
if (filename === appVuePath && !query.vue) {
debugSetup(filename);
return (code +
`;import { setupApp } from '@dcloudio/uni-h5';setupApp(_sfc_main);`);
}
if (query.mpType === 'page') {
debugSetup(filename);
return (code +
`;import { setupPage } from '@dcloudio/uni-h5';setupPage(_sfc_main);`);
}
},
};
}
exports.uniSetupPlugin = uniSetupPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSSRPlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const ENTRY_SERVER_JS = 'entry-server.js';
function uniSSRPlugin() {
let entryServerJs;
let resolvedConfig;
const entryServerJsCode = utils_1.generateSsrEntryServerCode();
return {
name: 'vite:uni-h5-ssr',
configResolved(config) {
resolvedConfig = config;
entryServerJs = path_1.default.join(process.env.UNI_INPUT_DIR, ENTRY_SERVER_JS);
if (utils_1.isSsr(resolvedConfig.command, resolvedConfig)) {
const { MODE } = uni_cli_shared_1.parseCompatConfigOnce(process.env.UNI_INPUT_DIR);
utils_1.initSsrDefine(resolvedConfig);
utils_1.rewriteSsrVue(MODE);
utils_1.rewriteSsrResolve(MODE);
utils_1.rewriteSsrNativeTag();
utils_1.rewriteSsrRenderStyle(process.env.UNI_INPUT_DIR);
}
},
resolveId(id) {
if (id.endsWith(ENTRY_SERVER_JS)) {
return entryServerJs;
}
},
load(id) {
if (id.endsWith(ENTRY_SERVER_JS)) {
return entryServerJsCode;
}
},
generateBundle(_options, bundle) {
const chunk = bundle['entry-server.js'];
if (chunk) {
chunk.code =
utils_1.generateSsrDefineCode(resolvedConfig, uni_cli_shared_1.parseRpx2UnitOnce(process.env.UNI_INPUT_DIR)) +
'\n' +
chunk.code;
}
},
};
}
exports.uniSSRPlugin = uniSSRPlugin;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDefine = exports.initFeatures = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const ssr_1 = require("./ssr");
function initProjectFeature({ command }) {
const features = {};
if (command === 'build') {
}
return features;
}
function initPagesFeature({ pagesJson, command, inputDir, ssr, }) {
const features = {
nvue: true,
pages: true,
tabBar: true,
tabBarMidButton: true,
topWindow: false,
leftWindow: false,
rightWindow: false,
navigationBar: true,
pullDownRefresh: false,
navigationBarButtons: true,
navigationBarSearchInput: true,
navigationBarTransparent: true,
};
const { tabBar, pages, topWindow, leftWindow, rightWindow, globalStyle } = pagesJson;
// ssr 时强制启用多页面(需要用到router)
if (!ssr && pages && pages.length === 1) {
features.pages = false;
}
if (!(tabBar && tabBar.list && tabBar.list.length)) {
features.tabBar = false;
features.tabBarMidButton = false;
}
if (features.tabBar && !tabBar.midButton) {
features.tabBarMidButton = false;
}
if (topWindow && topWindow.path) {
features.topWindow = true;
}
if (leftWindow && leftWindow.path) {
features.leftWindow = true;
}
if (rightWindow && rightWindow.path) {
features.rightWindow = true;
}
if (globalStyle.enablePullDownRefresh) {
features.pullDownRefresh = true;
}
else {
if (pages.find((page) => page.style && page.style.enablePullDownRefresh)) {
features.pullDownRefresh = true;
}
}
if (command === 'build') {
if (!pages.find((page) => fs_1.default.existsSync(path_1.default.resolve(inputDir, page.path + '.nvue')))) {
features.nvue = false;
}
let isNavigationCustom = false;
if (globalStyle.navigationBar.style === 'custom') {
isNavigationCustom = true; // 全局custom
if (pages.find((page) => page.style.navigationBar.style === 'default')) {
isNavigationCustom = false;
}
}
else {
// 所有页面均custom
if (pages.every((page) => page.style.navigationBar.style === 'custom')) {
isNavigationCustom = true;
}
}
if (isNavigationCustom) {
features.navigationBar = false;
features.navigationBarButtons = false;
features.navigationBarSearchInput = false;
features.navigationBarTransparent = false;
}
else {
if (!pages.find((page) => shared_1.isArray(page.style.navigationBar.buttons) &&
page.style.navigationBar.buttons.length)) {
features.navigationBarButtons = false;
}
if (!globalStyle.navigationBar.searchInput &&
!pages.find((page) => page.style.navigationBar.searchInput)) {
features.navigationBarSearchInput = false;
}
if (globalStyle.navigationBar.type !== 'transparent' &&
!pages.find((page) => page.style.navigationBar.type === 'transparent')) {
features.navigationBarTransparent = false;
}
}
}
return features;
}
function initManifestFeature({ manifestJson, command, platform, }) {
const features = {
wx: false,
wxs: true,
rpx: true,
promise: false,
longpress: true,
routerMode: '"hash"',
i18nEn: true,
i18nEs: true,
i18nFr: true,
i18nZhHans: true,
i18nZhHant: true,
vueOptionsApi: true,
vueProdDevTools: false,
};
if (command === 'build') {
// TODO 需要预编译一遍?
features.wxs = true;
features.longpress = true;
}
if (manifestJson.h5 &&
manifestJson.h5.router &&
manifestJson.h5.router.mode === 'history') {
features.routerMode = '"history"';
}
const platformJson = manifestJson[platform] || {};
const manifestFeatures = platformJson.features;
if (manifestFeatures) {
const { i18n } = manifestFeatures;
if (shared_1.isArray(i18n)) {
if (!i18n.includes('en')) {
features.i18nEn = false;
}
if (!i18n.includes('es')) {
features.i18nEs = false;
}
if (!i18n.includes('fr')) {
features.i18nFr = false;
}
if (!i18n.includes('zh-Hans')) {
features.i18nZhHans = false;
}
if (!i18n.includes('zh-Hant')) {
features.i18nZhHant = false;
}
}
}
// TODO other features
return features;
}
function initFeatures(options) {
const { wx, wxs, rpx, nvue, i18nEn, i18nEs, i18nFr, i18nZhHans, i18nZhHant, vueOptionsApi, vueProdDevTools, pages, tabBar, tabBarMidButton, promise, longpress, routerMode, topWindow, leftWindow, rightWindow, navigationBar, pullDownRefresh, navigationBarButtons, navigationBarSearchInput, navigationBarTransparent, } = shared_1.extend(initManifestFeature(options), initPagesFeature(options), initProjectFeature(options));
const features = {
// vue
__VUE_OPTIONS_API__: vueOptionsApi,
__VUE_PROD_DEVTOOLS__: vueProdDevTools,
// uni
__UNI_FEATURE_WX__: wx,
__UNI_FEATURE_WXS__: wxs,
__UNI_FEATURE_RPX__: rpx,
__UNI_FEATURE_PROMISE__: promise,
__UNI_FEATURE_LONGPRESS__: longpress,
__UNI_FEATURE_I18N_EN__: i18nEn,
__UNI_FEATURE_I18N_ES__: i18nEs,
__UNI_FEATURE_I18N_FR__: i18nFr,
__UNI_FEATURE_I18N_ZH_HANS__: i18nZhHans,
__UNI_FEATURE_I18N_ZH_HANT__: i18nZhHant,
// 以下特性,编译器已自动识别是否需要启用
__UNI_FEATURE_NVUE__: nvue,
__UNI_FEATURE_ROUTER_MODE__: routerMode,
__UNI_FEATURE_PAGES__: pages,
__UNI_FEATURE_TABBAR__: tabBar,
__UNI_FEATURE_TABBAR_MIDBUTTON__: tabBarMidButton,
__UNI_FEATURE_TOPWINDOW__: topWindow,
__UNI_FEATURE_LEFTWINDOW__: leftWindow,
__UNI_FEATURE_RIGHTWINDOW__: rightWindow,
__UNI_FEATURE_RESPONSIVE__: topWindow || leftWindow || rightWindow,
__UNI_FEATURE_NAVIGATIONBAR__: navigationBar,
__UNI_FEATURE_PULL_DOWN_REFRESH__: pullDownRefresh,
__UNI_FEATURE_NAVIGATIONBAR_BUTTONS__: navigationBarButtons,
__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__: navigationBarSearchInput,
__UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__: navigationBarTransparent, // 是否启用透明标题栏
};
// ssr nodejs features
if (options.ssr) {
Object.keys(features).forEach((name) => {
const value = features[name];
shared_1.extend(globalThis, {
[name]: shared_1.isString(value) ? JSON.parse(value) : value,
});
});
}
return features;
}
exports.initFeatures = initFeatures;
function createDefine(command, config) {
const platform = process.env.UNI_PLATFORM;
const inputDir = process.env.UNI_INPUT_DIR;
return initFeatures({
inputDir,
command,
platform,
pagesJson: uni_cli_shared_1.parsePagesJsonOnce(inputDir, platform),
manifestJson: uni_cli_shared_1.parseManifestJsonOnce(inputDir),
ssr: ssr_1.isSsr(command, config) || ssr_1.isSsrManifest(command, config),
});
}
exports.createDefine = createDefine;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./ssr"), exports);
__exportStar(require("./features"), exports);
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteSsrRenderStyle = exports.rewriteSsrNativeTag = exports.rewriteSsrResolve = exports.rewriteSsrVue = exports.generateSsrEntryServerCode = exports.generateSsrDefineCode = exports.initSsrDefine = exports.isSsrManifest = exports.isSsr = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function isSsr(command, config) {
if (command === 'serve') {
return !!(config.server && config.server.middlewareMode);
}
if (command === 'build') {
return !!(config.build && config.build.ssr);
}
return false;
}
exports.isSsr = isSsr;
function isSsrManifest(command, config) {
if (command === 'build') {
return !!(config.build && config.build.ssrManifest);
}
return false;
}
exports.isSsrManifest = isSsrManifest;
function initSsrDefine(config) {
return shared_1.extend(globalThis, {
__IMPORT_META_ENV_BASE_URL__: config.env.BASE_URL,
});
}
exports.initSsrDefine = initSsrDefine;
function serializeDefine(define) {
let res = `{`;
for (const key in define) {
const val = define[key];
res += `${JSON.stringify(key)}: ${typeof val === 'string' ? `(${val})` : JSON.stringify(val)}, `;
}
return res + `}`;
}
function normalizeSsrDefine(config) {
const defines = shared_1.extend({
__IMPORT_META_ENV_BASE_URL__: JSON.stringify(config.env.BASE_URL),
}, config.define);
delete defines['import.meta.env.LEGACY'];
return defines;
}
function generateSsrDefineCode(config, { unit, unitRatio, unitPrecision }) {
return fs_extra_1.default
.readFileSync(path_1.default.join(__dirname, '../../lib/ssr/define.js'), 'utf8')
.replace('__DEFINES__', serializeDefine(normalizeSsrDefine(config)))
.replace('__UNIT__', JSON.stringify(unit))
.replace('__UNIT_RATIO__', JSON.stringify(unitRatio))
.replace('__UNIT_PRECISION__', JSON.stringify(unitPrecision));
}
exports.generateSsrDefineCode = generateSsrDefineCode;
function generateSsrEntryServerCode() {
return fs_extra_1.default.readFileSync(path_1.default.join(__dirname, '../../lib/ssr/entry-server.js'), 'utf8');
}
exports.generateSsrEntryServerCode = generateSsrEntryServerCode;
function rewriteSsrVue(mode) {
// 解决 @vue/server-renderer 中引入 vue 的映射
let vuePath;
if (mode === 2) {
vuePath = uni_cli_shared_1.resolveBuiltIn('@dcloudio/uni-h5-vue/dist/vue.runtime.compat.cjs.js');
}
else {
vuePath = uni_cli_shared_1.resolveBuiltIn('@dcloudio/uni-h5-vue/dist/vue.runtime.cjs.js');
}
require('module-alias').addAlias('vue', vuePath);
}
exports.rewriteSsrVue = rewriteSsrVue;
function initResolveSyncOpts(opts) {
if (!opts) {
opts = {};
}
if (!opts.paths) {
opts.paths = [];
}
if (shared_1.isString(opts.paths)) {
opts.paths = [opts.paths];
}
if (shared_1.isArray(opts.paths)) {
opts.paths.push(path_1.default.join(process.env.UNI_CLI_CONTEXT, 'node_modules'));
}
return opts;
}
function rewriteSsrResolve(mode) {
// 解决 ssr 时 __vite_ssr_import__("vue") 的映射
const resolve = require('resolve');
const oldSync = resolve.sync;
resolve.sync = (id, opts) => {
if (id === 'vue') {
return uni_cli_shared_1.resolveBuiltIn(`@dcloudio/uni-h5-vue/dist/vue.runtime.${mode === 2 ? 'compat.' : ''}cjs.js`);
}
return oldSync(id, initResolveSyncOpts(opts));
};
}
exports.rewriteSsrResolve = rewriteSsrResolve;
function rewriteSsrNativeTag() {
const { parserOptions } = require('@vue/compiler-dom');
// TODO compiler-ssr时,传入的 isNativeTag 会被 @vue/compiler-dom 的 isNativeTag 覆盖
// https://github.com/vuejs/vue-next/blob/master/packages/compiler-ssr/src/index.ts#L36
parserOptions.isNativeTag = uni_shared_1.isNativeTag;
}
exports.rewriteSsrNativeTag = rewriteSsrNativeTag;
function rewriteSsrRenderStyle(inputDir) {
const { unit, unitRatio, unitPrecision } = uni_cli_shared_1.parseRpx2UnitOnce(inputDir);
const rpx2unit = uni_shared_1.createRpx2Unit(unit, unitRatio, unitPrecision);
const shared = require('@vue/shared');
const oldStringifyStyle = shared.stringifyStyle;
shared.stringifyStyle = (styles) => rpx2unit(oldStringifyStyle(styles));
const serverRender = require('@vue/server-renderer');
const oldSsrRenderStyle = serverRender.ssrRenderStyle;
// 仅对字符串类型做转换,非字符串类型,通过 stringifyStyle 转换
serverRender.ssrRenderStyle = (raw) => shared_1.isString(raw) ? rpx2unit(oldSsrRenderStyle(raw)) : oldSsrRenderStyle(raw);
}
exports.rewriteSsrRenderStyle = rewriteSsrRenderStyle;
......@@ -40,7 +40,7 @@
"@types/sass": "^1.16.0"
},
"uni-app": {
"compilerVersion": "3.2.1"
"compilerVersion": "3.2.2"
},
"gitHead": "4dd0e035b52584ff028ee3028c46adc555be0529"
}
import { extend } from '@vue/shared'
import { RollupWatcher } from 'rollup'
import { BuildOptions, ServerOptions } from 'vite'
import {
TIPS_BUILD_COMPLETE,
TIPS_WATCH_FOR_CHANGES,
} from '@dcloudio/uni-cli-shared'
import { M } from '@dcloudio/uni-cli-shared'
import { CliOptions } from '.'
import { build, buildSSR } from './build'
import { createServer, createSSRServer } from './server'
......@@ -19,9 +16,11 @@ export async function runDev(options: CliOptions & ServerOptions) {
} else {
const watcher = (await build(options)) as RollupWatcher
watcher.on('event', (event) => {
if (event.code === 'BUNDLE_END') {
if (event.code === 'BUNDLE_START') {
console.log(M['dev.watching.start'])
} else if (event.code === 'BUNDLE_END') {
event.result.close()
console.log(TIPS_WATCH_FOR_CHANGES)
console.log(M['dev.watching.end'])
}
})
}
......@@ -41,7 +40,7 @@ export async function runBuild(options: CliOptions & BuildOptions) {
await (options.ssr && options.platform === 'h5'
? buildSSR(options)
: build(options))
console.log(TIPS_BUILD_COMPLETE)
console.log(M['build.done'])
} catch (e) {
console.error(`error during build:\n${e.stack || e}`)
process.exit(1)
......
......@@ -30,7 +30,6 @@ export function createConfig(
base = '/'
}
options.base = base!
return {
base,
root: process.env.VITE_ROOT_DIR,
......
import path from 'path'
import { ResolvedConfig } from 'vite'
import { M } from '@dcloudio/uni-cli-shared'
export function initEnv(config: ResolvedConfig) {
if (!process.env.UNI_PLATFORM) {
process.env.UNI_PLATFORM = 'h5'
......@@ -14,4 +16,12 @@ export function initEnv(config: ResolvedConfig) {
if (!process.env.UNI_OUTPUT_DIR) {
process.env.UNI_OUTPUT_DIR = path.resolve(config.root, config.build.outDir)
}
if (!config.isProduction) {
console.log(
M['dev.performance'] +
(process.env.UNI_PLATFORM.startsWith('mp-')
? M['dev.performance.mp']
: '')
)
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册