plugin-light
Version:
Webpack 相关插件、Loader、基础配置及 CLI 命令
890 lines (856 loc) • 37.7 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var fs = require('fs');
var path = require('path');
var tComm = require('t-comm');
var webpack = require('webpack');
var webpackBundleAnalyzer = require('webpack-bundle-analyzer');
var TransformPages = require('uni-read-pages');
var ProgressBarPlugin = require('progress-bar-webpack-plugin');
var chalk = require('chalk');
var ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
var WorkboxPlugin = require('workbox-webpack-plugin');
var plugin = require('plugin-light/lib/plugin');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
var path__namespace = /*#__PURE__*/_interopNamespace(path);
var webpack__default = /*#__PURE__*/_interopDefaultLegacy(webpack);
var TransformPages__default = /*#__PURE__*/_interopDefaultLegacy(TransformPages);
var ProgressBarPlugin__default = /*#__PURE__*/_interopDefaultLegacy(ProgressBarPlugin);
var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
var ScriptExtHtmlWebpackPlugin__default = /*#__PURE__*/_interopDefaultLegacy(ScriptExtHtmlWebpackPlugin);
var WorkboxPlugin__default = /*#__PURE__*/_interopDefaultLegacy(WorkboxPlugin);
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _toPrimitive(input, hint) {
if (_typeof(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return _typeof(key) === "symbol" ? key : String(key);
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function getRootDir() {
return process.cwd();
}
var publishUtil = "./webpack-publish.js";
var vueDirective = "./loader/vue-directive.js";
var vueDirectiveProd = "./loader/vue-directive.prod.js";
var vLazy = "./loader/v-lazy.js";
var vLazyProd = "./loader/v-lazy.prod.js";
var transformDynamicComp = "./loader/transform-dynamic-comp.js";
var transformDynamicCompProd = "./loader/transform-dynamic-comp.prod.js";
var swipeComponent = "./loader/swipe-component.js";
var swipeComponentProd = "./loader/swipe-component.prod.js";
var replaceVueKey = "./loader/replace-vue-key.js";
var replaceVueKeyProd = "./loader/replace-vue-key.prod.js";
var replaceTemplateTag = "./loader/replace-template-tag.js";
var replaceTemplateTagProd = "./loader/replace-template-tag.prod.js";
var replaceLibrary = "./loader/replace-library.js";
var replaceLibraryProd = "./loader/replace-library.prod.js";
var replaceContent = "./loader/replace-content.js";
var replaceContentProd = "./loader/replace-content.prod.js";
var insertPageMeta = "./loader/insert-page-meta.js";
var insertPageMetaProd = "./loader/insert-page-meta.prod.js";
var insertGlobalComp = "./loader/insert-global-comp.js";
var insertGlobalCompProd = "./loader/insert-global-comp.prod.js";
var injectDynamicStyleWeb = "./loader/inject-dynamic-style-web.js";
var injectDynamicStyleWebProd = "./loader/inject-dynamic-style-web.prod.js";
var injectDynamicStyleMp = "./loader/inject-dynamic-style-mp.js";
var injectDynamicStyleMpProd = "./loader/inject-dynamic-style-mp.prod.js";
var ifdefLoader = "./loader/ifdef-loader.js";
var ifdefLoaderProd = "./loader/ifdef-loader.prod.js";
var ifdef = "./loader/ifdef.js";
var ifdefProd = "./loader/ifdef.prod.js";
var cssUrlBlankSpace = "./loader/css-url-blank-space.js";
var cssUrlBlankSpaceProd = "./loader/css-url-blank-space.prod.js";
var crossPlatform = "./loader/cross-platform.js";
var crossPlatformProd = "./loader/cross-platform.prod.js";
var crossModuleStyle = "./loader/cross-module-style.js";
var crossModuleStyleProd = "./loader/cross-module-style.prod.js";
var crossGameStyle = "./loader/cross-game-style.js";
var crossGameStyleProd = "./loader/cross-game-style.prod.js";
var autoPlaceholder = "./loader/auto-placeholder.js";
var autoPlaceholderProd = "./loader/auto-placeholder.prod.js";
var LoaderMap = {
publishUtil: publishUtil,
vueDirective: vueDirective,
vueDirectiveProd: vueDirectiveProd,
vLazy: vLazy,
vLazyProd: vLazyProd,
transformDynamicComp: transformDynamicComp,
transformDynamicCompProd: transformDynamicCompProd,
swipeComponent: swipeComponent,
swipeComponentProd: swipeComponentProd,
replaceVueKey: replaceVueKey,
replaceVueKeyProd: replaceVueKeyProd,
replaceTemplateTag: replaceTemplateTag,
replaceTemplateTagProd: replaceTemplateTagProd,
replaceLibrary: replaceLibrary,
replaceLibraryProd: replaceLibraryProd,
replaceContent: replaceContent,
replaceContentProd: replaceContentProd,
insertPageMeta: insertPageMeta,
insertPageMetaProd: insertPageMetaProd,
insertGlobalComp: insertGlobalComp,
insertGlobalCompProd: insertGlobalCompProd,
injectDynamicStyleWeb: injectDynamicStyleWeb,
injectDynamicStyleWebProd: injectDynamicStyleWebProd,
injectDynamicStyleMp: injectDynamicStyleMp,
injectDynamicStyleMpProd: injectDynamicStyleMpProd,
ifdefLoader: ifdefLoader,
ifdefLoaderProd: ifdefLoaderProd,
ifdef: ifdef,
ifdefProd: ifdefProd,
cssUrlBlankSpace: cssUrlBlankSpace,
cssUrlBlankSpaceProd: cssUrlBlankSpaceProd,
crossPlatform: crossPlatform,
crossPlatformProd: crossPlatformProd,
crossModuleStyle: crossModuleStyle,
crossModuleStyleProd: crossModuleStyleProd,
crossGameStyle: crossGameStyle,
crossGameStyleProd: crossGameStyleProd,
autoPlaceholder: autoPlaceholder,
autoPlaceholderProd: autoPlaceholderProd
};
function getLoaderMap() {
return Object.keys(LoaderMap).reduce(function (acc, key) {
acc[key] = path__namespace.resolve(__dirname, LoaderMap[key]);
return acc;
}, {});
}
var LOADER_MAP = getLoaderMap();
var config = {};
Object.defineProperty(config, '__esModule', { value: true });
var BUILD_NAME_MAP = {
build: '_vConsoleBuildInfo',
commit: '_vConsoleCommitInfo'
};
var V_CONSOLE_DOM = {
LINE: 'line',
WRAP: 'v-console-custom-tab',
URL_INPUT_ID: 'vConsolePluginInput',
URL_JUMP_BUTTON: 'vConsolePluginUrlJumpButton',
GO_BACK_BUTTON: 'vConsolePluginGoBackButton',
PLUGIN_NAME_PREFIX: '__vc_plug_',
// 需要小写,作为插件 id
PLUGIN_VERSION_NAME: 'version_performance',
PLUGIN_SIMPLE_VERSION_NAME: 'simple_version'
};
var EMPTY_LINE = "<div class=\"".concat(V_CONSOLE_DOM.LINE, "\"> </div>");
var V_CONSOLE_NO_DELAY = {
KEY: 'vConsole_no_delay',
VALUE: '1'
};
var V_CONSOLE_URL = 'https://image-1251917893.file.myqcloud.com/igame/npm/vconsole%403.15.1/vconsole.min.js';
var V_CONSOLE_STYLE_CONTENT = "\n.".concat(V_CONSOLE_DOM.WRAP, " {\n padding: 12px 16px 30px;\n user-select: auto;\n}\n\n.").concat(V_CONSOLE_DOM.WRAP, " .").concat(V_CONSOLE_DOM.LINE, " {\n line-height: 20px;\n padding: 5px 0;\n color: var(--VC-PURPLE, #6467f0);\n word-break: break-all;\n user-select: auto;\n}\n\n.").concat(V_CONSOLE_DOM.WRAP, " textarea {\n display: block;\n width: 100%;\n min-width: 0;\n padding: 0;\n color: #323233;\n line-height: inherit;\n text-align: left;\n background-color: transparent;\n resize: none;\n border: 1px solid #ddd;\n border-radius: 3px;\n margin-bottom: 10px;\n height: 60px;\n padding: 4px;\n line-height: 16px;\n font-size: 13px;\n user-select: auto;\n}\n\n.").concat(V_CONSOLE_DOM.WRAP, " textarea:focus {\n outline: none;\n}\n\n.").concat(V_CONSOLE_DOM.WRAP, " button {\n height: 30px;\n line-height: 1.2;\n text-align: center;\n border-radius: 2px;\n cursor: pointer;\n color: #fff;\n background-color: #07c160;\n border: 1px solid #07c160;\n font-size: 14px;\n padding: 0 12px;\n margin-right: 10px;\n}\n\n.vc-cmd,\n.vc-cmd-input {\n user-select: auto !important;\n}\n\n#").concat(V_CONSOLE_DOM.URL_INPUT_ID, " {\n user-select: auto !important;\n}\n");
var DEBUG_CGI_ENV = {
KEY: 'tip_debug_cgi_env',
PROD: 'prod',
TEST: 'test'
};
var BUILD_LIST = [{
key: 'time',
label: 'Build Time'
}, {
key: 'author',
label: 'Build Author'
}, {
key: 'branch',
label: 'Build Branch'
}, {
key: 'netEnv',
label: 'Build Net Env'
}];
var COMMIT_LIST = [{
key: 'message',
label: 'Last Commit Message'
}, {
key: 'author',
label: 'Last Commit Author'
}, {
key: 'date',
label: 'Last Commit Time'
}, {
key: 'hash',
label: 'Last Commit Hash'
}];
var AEGIS_PERFORMANCE_KEY = '__AEGIS_PERFORMANCE';
var AEGIS_PERFORMANCE_LIST = [{
key: 'dnsLookup',
label: 'Aegis DNS 查询'
}, {
key: 'tcp',
label: 'Aegis TCP 链接'
}, {
key: 'ttfb',
label: 'Aegis SSL 建连'
}, {
key: 'contentDownload',
label: 'Aegis contentDownload'
}, {
key: 'resourceDownload',
label: 'Aegis resourceDownload'
}, {
key: 'domParse',
label: 'Aegis DOM解析'
}, {
key: 'firstScreenTiming',
label: 'Aegis 首屏耗时'
}];
config.AEGIS_PERFORMANCE_KEY = AEGIS_PERFORMANCE_KEY;
config.AEGIS_PERFORMANCE_LIST = AEGIS_PERFORMANCE_LIST;
config.BUILD_LIST = BUILD_LIST;
var BUILD_NAME_MAP_1 = config.BUILD_NAME_MAP = BUILD_NAME_MAP;
config.COMMIT_LIST = COMMIT_LIST;
config.DEBUG_CGI_ENV = DEBUG_CGI_ENV;
config.EMPTY_LINE = EMPTY_LINE;
config.V_CONSOLE_DOM = V_CONSOLE_DOM;
config.V_CONSOLE_NO_DELAY = V_CONSOLE_NO_DELAY;
config.V_CONSOLE_STYLE_CONTENT = V_CONSOLE_STYLE_CONTENT;
config.V_CONSOLE_URL = V_CONSOLE_URL;
function getProjectName() {
var result = '';
try {
var json = tComm.readFileSync('package.json', true) || {};
result = json.name || '';
} catch (err) {}
return result;
}
function getSubProjectName() {
var _process$env$VUE_APP_;
var name = ((_process$env$VUE_APP_ = process.env.VUE_APP_DIR) === null || _process$env$VUE_APP_ === void 0 || (_process$env$VUE_APP_ = _process$env$VUE_APP_.split('/')) === null || _process$env$VUE_APP_ === void 0 ? void 0 : _process$env$VUE_APP_[1]) || '';
return name;
}
function checkH5() {
return process.env.VUE_APP_PLATFORM === 'h5';
}
var DEFAULT_TRANSPILE_DEPENDENCIES = ['pmd-merchant-ui', 'press-ui', 'press-plus', 'pmd-aegis', 'pmd-app-info', 'pmd-config', 'pmd-location', 'pmd-login', 'pmd-network', 'pmd-report', 'pmd-tools', 'pmd-types', 'pmd-widget', 'pmd-vue', 'pmd-jsapi', 'pmd-component', 'pmd-business', 'pmd-api', '@zebra-ui/swiper'
// /[@\\]tencent[/\\]press-ui/,
// /[@\\]tencent[/\\]press-plus/,
// /[@\\]tencent[/\\]pmd-aegis/,
// /[@\\]tencent[/\\]pmd-app-info/,
// /[@\\]tencent[/\\]pmd-config/,
// /[@\\]tencent[/\\]pmd-location/,
// /[@\\]tencent[/\\]pmd-login/,
// /[@\\]tencent[/\\]pmd-network/,
// /[@\\]tencent[/\\]pmd-report/,
// /[@\\]tencent[/\\]pmd-tools/,
// /[@\\]tencent[/\\]pmd-widget/,
// /[@\\]tencent[/\\]pmd-vue/,
// /[@\\]tencent[/\\]pmd-jsapi/,
// /[@\\]zebra-ui[/\\]swiper/,
];
var DEFAULT_ADAPTER_DIRS = ['comm', 'common', 'component', 'live-component', 'logic', 'local-logic', 'local-component', 'login', 'pages', 'static', 'node-modules'];
var AEGIS_EXTERNAL_SCRIPT_LINK = 'https://image-1251917893.file.myqcloud.com/igame/npm/aegis-web/aegis.min.js';
var UNI_SIMPLE_ROUTER_SCRIPT_LINK = 'https://image-1251917893.file.myqcloud.com/igame/npm/uni-simple-router/uni-simple-router-2.0.8-beta-4.js';
var EXTERNAL_LINK_MAP = {
AXIOS: 'https://image-1251917893.file.myqcloud.com/igame/npm/axios@0.18.0/dist/axios.min.js',
VUE_LAZY_LOAD: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-lazyload@1.3.3/vue-lazyload.js',
AEGIS_WEB: AEGIS_EXTERNAL_SCRIPT_LINK,
UNI_SIMPLE_ROUTER: UNI_SIMPLE_ROUTER_SCRIPT_LINK
};
function getExternals(_ref) {
var aegisWebSdkExternal = _ref.aegisWebSdkExternal,
uniSimpleRouterExternal = _ref.uniSimpleRouterExternal,
axiosExternal = _ref.axiosExternal,
vueLazyloadExternal = _ref.vueLazyloadExternal;
var externals = {};
if (checkH5()) {
if (aegisWebSdkExternal) {
externals['aegis-web-sdk'] = 'window Aegis';
}
if (uniSimpleRouterExternal) {
externals['uni-simple-router'] = 'Router';
}
if (axiosExternal) {
externals.axios = 'axios';
}
if (vueLazyloadExternal) {
externals['vue-lazyload'] = 'VueLazyload';
}
}
return externals;
}
function getExternalScripts(_ref2) {
var uniSimpleRouterExternal = _ref2.uniSimpleRouterExternal,
aegisWebSdkExternal = _ref2.aegisWebSdkExternal,
axiosExternal = _ref2.axiosExternal,
vueLazyloadExternal = _ref2.vueLazyloadExternal;
var externalScripts = [];
insertScript(externalScripts, EXTERNAL_LINK_MAP.AEGIS_WEB, aegisWebSdkExternal);
insertScript(externalScripts, EXTERNAL_LINK_MAP.AXIOS, axiosExternal);
insertScript(externalScripts, EXTERNAL_LINK_MAP.UNI_SIMPLE_ROUTER, uniSimpleRouterExternal);
insertScript(externalScripts, EXTERNAL_LINK_MAP.VUE_LAZY_LOAD, vueLazyloadExternal);
return externalScripts;
}
function insertScript(externalScripts, defaultScript, key) {
if (typeof key === 'string') {
externalScripts.push(key);
} else if (key) {
externalScripts.push(defaultScript);
}
}
// 读取 manifest.json ,修改后重新写入
var manifestPath = "".concat(process.env.UNI_INPUT_DIR, "/manifest.json");
var originManifest = fs__namespace.readFileSync(manifestPath, {
encoding: 'utf-8'
});
var Manifest = originManifest;
function replaceManifest(path, value) {
var arr = path.split('.');
var len = arr.length;
var lastItem = arr[len - 1];
var i = 0;
var ManifestArr = Manifest.split(/\n/);
for (var index = 0; index < ManifestArr.length; index++) {
var item = ManifestArr[index];
if (new RegExp("\"".concat(arr[i], "\"")).test(item)) i = i + 1;
if (i === len) {
var hasComma = /,/.test(item);
ManifestArr[index] = item.replace(new RegExp("\"".concat(lastItem, "\"[\\s\\S]*:[\\s\\S]*")), "\"".concat(lastItem, "\": ").concat(value).concat(hasComma ? ',' : ''));
break;
}
}
Manifest = ManifestArr.join('\n');
}
function updateManifest(path, value) {
replaceManifest(path, value);
fs__namespace.writeFileSync(manifestPath, Manifest, {
flag: 'w'
});
}
function checkBundleAnalyze() {
return process.argv.includes('--bundleAnalyzer') || !!process.env.npm_config_report;
}
function checkDebugMode() {
return !!process.env.DEBUG_MODE;
}
var CSS_MAP = {
MP_WX: '.wxss',
MP_QQ: '.qss',
MP_ALIPAY: '.acss',
MP_JD: '.jxss'
};
// TODO: 类型补充
var CSS_POSTFIX_MAP = Object.keys(CSS_MAP).reduce(function (acc, item) {
acc[item] = CSS_MAP[item].slice(1);
return acc;
}, {});
function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function getPlugins(_ref) {
var adapterDirs = _ref.adapterDirs,
_ref$useDispatchScrip = _ref.useDispatchScriptPlugin,
useDispatchScriptPlugin = _ref$useDispatchScrip === void 0 ? false : _ref$useDispatchScrip,
_ref$dispatchScriptPl = _ref.dispatchScriptPluginOptions,
dispatchScriptPluginOptions = _ref$dispatchScriptPl === void 0 ? {} : _ref$dispatchScriptPl,
_ref$useDispatchVuePl = _ref.useDispatchVuePlugin,
useDispatchVuePlugin = _ref$useDispatchVuePl === void 0 ? false : _ref$useDispatchVuePl,
_ref$dispatchVuePlugi = _ref.dispatchVuePluginOptions,
dispatchVuePluginOptions = _ref$dispatchVuePlugi === void 0 ? {} : _ref$dispatchVuePlugi,
_ref$useCopyDirPlugin = _ref.useCopyDirPlugin,
useCopyDirPlugin = _ref$useCopyDirPlugin === void 0 ? false : _ref$useCopyDirPlugin,
_ref$copyDirPluginOpt = _ref.copyDirPluginOptions,
copyDirPluginOptions = _ref$copyDirPluginOpt === void 0 ? {} : _ref$copyDirPluginOpt,
_ref$useAddPlaceHolde = _ref.useAddPlaceHolderPlugin,
useAddPlaceHolderPlugin = _ref$useAddPlaceHolde === void 0 ? false : _ref$useAddPlaceHolde,
_ref$remToRpxPluginMp = _ref.remToRpxPluginMpOptions,
remToRpxPluginMpOptions = _ref$remToRpxPluginMp === void 0 ? {} : _ref$remToRpxPluginMp,
_ref$genVersionWebPlu = _ref.genVersionWebPluginOptions,
genVersionWebPluginOptions = _ref$genVersionWebPlu === void 0 ? {
buildName: BUILD_NAME_MAP_1.build,
commitName: BUILD_NAME_MAP_1.commit,
delay: 1
} : _ref$genVersionWebPlu,
_ref$useFixMiniCssPlu = _ref.useFixMiniCssPlugin,
useFixMiniCssPlugin = _ref$useFixMiniCssPlu === void 0 ? false : _ref$useFixMiniCssPlu,
aegisWebSdkExternal = _ref.aegisWebSdkExternal,
uniSimpleRouterExternal = _ref.uniSimpleRouterExternal,
axiosExternal = _ref.axiosExternal,
vueLazyloadExternal = _ref.vueLazyloadExternal,
customPreload = _ref.customPreload,
useWorkBoxPlugin = _ref.useWorkBoxPlugin,
saveBundleAnalyzeHtml = _ref.saveBundleAnalyzeHtml,
useReplaceUniH5Plugin = _ref.useReplaceUniH5Plugin;
var plugins = [];
var isProduction = process.env.NODE_ENV === 'production';
if (process.env.VUE_APP_PLATFORM === 'app-plus') {
var globalVarsDefinePlugin = new webpack__default["default"].DefinePlugin({
location: 'window.location',
navigator: 'window.navigator',
localStorage: 'window.localStorage',
sessionStorage: 'window.sessionStorage',
globalVars: 'window.globalVars',
document: 'window.document',
app: 'window.app'
});
plugins.push(globalVarsDefinePlugin);
plugins.push(new plugin.RemToRpxPlugin({
unit: 'px',
factor: 50,
fileSuffix: ['css', 'scss', 'less', 'js', CSS_POSTFIX_MAP.MP_WX, CSS_POSTFIX_MAP.MP_QQ, CSS_POSTFIX_MAP.MP_ALIPAY, CSS_POSTFIX_MAP.MP_JD]
}));
} else if (process.env.VUE_APP_PLATFORM !== 'h5') {
var _globalVarsDefinePlugin = new webpack__default["default"].DefinePlugin({
window: 'globalThis.$window',
location: 'globalThis.$location',
navigator: 'globalThis.$navigator',
localStorage: 'globalThis.$localStorage',
sessionStorage: 'globalThis.$sessionStorage',
globalVars: 'globalThis.$globalVars',
document: 'globalThis.$document',
app: 'globalThis.$window.app',
top: 'globalThis.$window',
defaultIsTestNet: process.env.NET_ENV === 'test'
});
plugins.push(_globalVarsDefinePlugin);
plugins.push(new plugin.RemToRpxPlugin(remToRpxPluginMpOptions || {}));
plugins.push(new plugin.GenVersionMpPlugin({}));
plugins.push(new plugin.TransferLocalFilePlugin({
adapterDirs: adapterDirs,
isModifyRef: true
}));
plugins.push(new plugin.FixNpmPackagePlugin({}));
if (process.env.VUE_APP_PLATFORM === 'mp-qq') {
plugins.push(new plugin.GlobalThisPolyfillPlugin());
}
if (useDispatchVuePlugin) {
plugins.push(new plugin.DispatchVuePlugin(dispatchVuePluginOptions || {}));
}
if (useDispatchScriptPlugin) {
plugins.push(new plugin.DispatchScriptPlugin(dispatchScriptPluginOptions || {}));
}
if (useAddPlaceHolderPlugin) {
plugins.push(new plugin.AddPlaceHolderPlugin());
}
} else {
if (isProduction && process.env.VUE_APP_ROUTER_BASE && process.env.VUE_APP_ROUTER_BASE !== '/') {
updateManifest('h5.router.base', JSON.stringify(process.env.VUE_APP_ROUTER_BASE));
}
if (process.env.VUE_APP_BRANCH !== 'release' && process.env.UNI_OPT_TREESHAKINGNG) {
delete process.env.UNI_OPT_TREESHAKINGNG;
}
process.env.UNI_OUTPUT_DIR = "".concat((process.env.UNI_INPUT_DIR || '').replace('src/project', 'dist/project'), "/static");
plugins.push(new plugin.GenVersionWebPlugin(genVersionWebPluginOptions));
if (isProduction) {
plugins.push(new plugin.CheckLongConstantPlugin());
}
}
if (useCopyDirPlugin) {
plugins.push(new plugin.CopyDirPlugin(copyDirPluginOptions || {}));
}
plugins.push(new webpack__default["default"].DefinePlugin({
ROUTES: webpack__default["default"].DefinePlugin.runtimeValue(function () {
var tfPages = new TransformPages__default["default"]({
includes: ['path', 'name', 'aliasPath', 'meta']
});
return JSON.stringify(tfPages.routes);
}, true),
VERSION: new Date().getTime()
}));
if (checkBundleAnalyze()) {
plugins.push(new webpackBundleAnalyzer.BundleAnalyzerPlugin({
analyzerPort: 8888
}));
} else if (saveBundleAnalyzeHtml && isProduction) {
plugins.push(new webpackBundleAnalyzer.BundleAnalyzerPlugin(_objectSpread$2({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: 'my-bundle-analyze.html'
}, _typeof(saveBundleAnalyzeHtml) === 'object' ? saveBundleAnalyzeHtml : {})));
}
if (useFixMiniCssPlugin) {
plugins.push(new plugin.FixMiniCssPlugin());
}
plugins.push(new ProgressBarPlugin__default["default"]({
format: " build [:bar] ".concat(chalk__default["default"].green.bold(':percent'), " (:elapsed seconds)"),
clear: false
}));
var externalScripts = getExternalScripts({
aegisWebSdkExternal: aegisWebSdkExternal,
uniSimpleRouterExternal: uniSimpleRouterExternal,
axiosExternal: axiosExternal,
vueLazyloadExternal: vueLazyloadExternal
});
if (externalScripts.length && checkH5()) {
plugins.push(new plugin.InsertScriptPlugin({
scripts: externalScripts
}));
}
if (customPreload && checkH5()) {
plugins.push.apply(plugins, [new plugin.CustomPreloadPlugin(customPreload), new plugin.ManifestExposePlugin(), new ScriptExtHtmlWebpackPlugin__default["default"]({
inline: /runtime/
})]);
}
if (useReplaceUniH5Plugin && checkH5()) {
plugins.push(new plugin.ReplaceUniH5Plugin(useReplaceUniH5Plugin));
}
if (checkH5() && useWorkBoxPlugin && isProduction) {
plugins.push(new WorkboxPlugin__default["default"].GenerateSW(_objectSpread$2({
swDest: "./service-worker-".concat(getProjectName(), "-").concat(getSubProjectName(), ".js"),
clientsClaim: true,
include: [/.*(.js|.css|.svg|.png|.jpg|.jpeg)/],
skipWaiting: true,
maximumFileSizeToCacheInBytes: 25 * 1024 * 1024,
importScripts: [],
inlineWorkboxRuntime: true,
runtimeCaching: [{
urlPattern: new RegExp('^https://image-1251917893\\.file\\.myqcloud.com.*(\\.js|\\.css|\\.svg|\\.png|\\.jpg|\\.jpeg)'),
handler: 'StaleWhileRevalidate',
options: {
cacheableResponse: {
statuses: [0, 200]
}
}
}, {
urlPattern: /.*\.html$/,
handler: 'NetworkOnly'
}]
}, useWorkBoxPlugin)));
}
return plugins;
}
function chainWebpack(config) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var useXSS = options.useXSS;
if (options.useInsertGlobalCompLoader) {
config.module.rule('global-comp-vue').test(/\.vue$/).pre().use(LOADER_MAP.insertGlobalComp).loader(LOADER_MAP.insertGlobalComp).options(options.insertGlobalCompLoaderOptions || {}).end();
}
if (options.useTransformDynamicCompLoader || options.useAddPlaceHolderPlugin) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.transformDynamicComp).loader(LOADER_MAP.transformDynamicComp).end();
}
if (options.useAddPlaceHolderPlugin) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.autoPlaceholder).loader(LOADER_MAP.autoPlaceholder).end();
}
if (options.useReplaceVueKeyLoader) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.replaceVueKey).loader(LOADER_MAP.replaceVueKey).end();
}
if (options.useReplaceTemplateTagLoader) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.replaceTemplateTag).loader(LOADER_MAP.replaceTemplateTag).options(options.replaceTemplateTagLoaderOptions || {}).end();
}
if (options.useVLazyLoader) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.vLazy).loader(LOADER_MAP.vLazy).options(options.vLazyLoaderOptions || {}).end();
}
if (options.useSwipeComponentLoader) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.swipeComponent).loader(LOADER_MAP.swipeComponent).end();
}
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.crossPlatform).loader(LOADER_MAP.crossPlatform).end().use(LOADER_MAP.crossGameStyle) // 处理样式的loader,必须在vue-loader前执行
.loader(LOADER_MAP.crossGameStyle).end().use(LOADER_MAP.crossModuleStyle).loader(LOADER_MAP.crossModuleStyle).options(options.crossModuleStyleLoaderOptions || {}).end().use('vue-loader').loader('vue-loader').tap(function (options) {
if (options !== null && options !== void 0 && options.compilerOptions) {
options.compilerOptions.whitespace = 'preserve';
}
return options;
}).tap(function (options) {
if (useXSS && options !== null && options !== void 0 && options.compilerOptions) {
options.compilerOptions.directives = {
html: function html(node, directiveMeta) {
(node.props || (node.props = [])).push({
name: 'innerHTML',
value: "xss(_s(".concat(directiveMeta.value, "))")
});
}
};
}
return options;
}).end();
if (options.useInsertPageMetaLoader) {
config.module.rule('vue').test(/\.vue$/).use(LOADER_MAP.insertPageMeta).loader(LOADER_MAP.insertPageMeta).options(options.insertPageMetaLoaderOptions || {}).end();
}
config.module.rule('cross-platform-prod').test(/\.[jt]s$/).use(LOADER_MAP.crossPlatformProd).loader(LOADER_MAP.crossPlatformProd).end();
if (options.useReplaceLibraryLoader) {
config.module.rule('replace-library').test(/\.(ts|js|vue)$/).use(LOADER_MAP.replaceLibrary).loader(LOADER_MAP.replaceLibrary).options(options.replaceLibraryLoaderOptions || {}).end();
}
// 发行或运行时启用了压缩时会生效;
config.optimization.minimizer('terser').tap(function (args) {
var compress = args[0].terserOptions.compress;
// 非 App 平台移除 console 代码(包含所有 console 方法,如 log,debug,info...)
compress.drop_console = process.env.VUE_APP_BRANCH === 'release';
compress.pure_funcs = ['__f__' // App 平台 vue 移除日志代码
// 'console.debug' // 可移除指定的 console 方法
];
return args;
});
}
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function optimizationH5(useH5SplitChunks) {
var _require = require('@dcloudio/uni-cli-shared'),
getMainEntry = _require.getMainEntry,
getH5Options = _require.getH5Options;
var _getH5Options = getH5Options(),
title = _getH5Options.title,
publicPath = _getH5Options.publicPath,
template = _getH5Options.template;
return {
pages: {
index: {
entry: path__namespace.resolve(process.env.UNI_INPUT_DIR, getMainEntry()),
// 模板来源
template: template,
filename: 'index.html',
title: title,
publicPath: publicPath,
chunks: ['uni-h5', 'core-js', 'vue-cli-plugin-uni', 'chunk-vendors', 'index', 'runtime',
// 'tencent-cloud-chat',
'pmd-vue']
}
},
chainWebpack: function chainWebpack(config) {
config.optimization.splitChunks(_objectSpread$1({
// chunks: 'all',
minChunks: 1,
maxInitialRequests: 20,
// maxAsyncRequests: 30,
cacheGroups: {
tim_js_sdk: {
name: 'tim-js-sdk',
test: /[\\/]node_modules[\\/]_?tim-js-sdk(.*)/,
priority: 15,
chunks: 'all',
// minSize: 0,
reuseExistingChunk: true
},
tencent_cloud_chat: {
name: 'tencent-cloud-chat',
test: /node_modules[\\/]_?[\\/]_?chat/,
chunks: 'all',
priority: 30,
reuseExistingChunk: true
},
pmd_vue: {
name: 'pmd-vue',
test: /node_modules[\\/]_?[\\/]_?pmd-vue/,
chunks: 'all',
priority: 30,
reuseExistingChunk: true
},
uni_h5: {
name: 'uni-h5',
test: /node_modules(.*)uni-h5(.*)/,
chunks: 'all',
priority: 20,
reuseExistingChunk: true
},
vue_cli_plugin_uni: {
name: 'vue-cli-plugin-uni',
test: /vue-cli-plugin-uni[\\/]_?packages/,
chunks: 'initial',
priority: 30,
reuseExistingChunk: true
},
core_js: {
name: 'core-js',
test: /[\\/]node_modules[\\/]_??core-js(.*)/,
chunks: 'initial',
priority: 30,
reuseExistingChunk: true
},
vendors: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial',
reuseExistingChunk: true
},
"default": {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
// index_home: {
// name: 'index-home',
// test: path.resolve('src/project/user/views/index'),
// priority: 60,
// chunks: 'all',
// reuseExistingChunk: true,
// },
}
}, typeof useH5SplitChunks === 'boolean' ? {} : useH5SplitChunks));
}
};
}
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var curDirname = getRootDir();
function getDefaultNeedSourceMap() {
var needSourceMap = checkH5() && process.env.NODE_ENV === 'production' && tComm.getGitCurBranch(__dirname) === 'release';
return needSourceMap;
}
// 获取目下所有项目文件夹名称并创建webpack别名
function getAllAppNameAlias() {
var usePMDBusinessAlias = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var files = fs__namespace.readdirSync(path__namespace.resolve(curDirname, 'src'));
var result = {
foldername: [],
filename: [] // 文件名,有后缀
};
files.forEach(function (file) {
var pathname = path__namespace.join(curDirname, 'src', file);
var stat = fs__namespace.lstatSync(pathname);
if (!stat.isDirectory()) {
result.filename.push(file);
} else {
result.foldername.push(file);
}
});
var rootDir = 'src';
var alias = {
src: path__namespace.resolve(curDirname, rootDir),
'@': path__namespace.resolve(process.env.UNI_INPUT_DIR || '') // 由环境变量确定当前的项目
};
result.foldername.forEach(function (dir) {
alias[dir] = path__namespace.resolve(curDirname, rootDir, dir);
});
if (usePMDBusinessAlias) {
return _objectSpread(_objectSpread({}, alias), {}, {
'src/component': 'pmd-business'
});
}
return alias;
}
function getUniVueConfig() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _ref = options || {},
useDispatchScriptPlugin = _ref.useDispatchScriptPlugin,
dispatchScriptPluginOptions = _ref.dispatchScriptPluginOptions,
useDispatchVuePlugin = _ref.useDispatchVuePlugin,
dispatchVuePluginOptions = _ref.dispatchVuePluginOptions,
useCopyDirPlugin = _ref.useCopyDirPlugin,
copyDirPluginOptions = _ref.copyDirPluginOptions,
useAddPlaceHolderPlugin = _ref.useAddPlaceHolderPlugin,
remToRpxPluginMpOptions = _ref.remToRpxPluginMpOptions,
genVersionWebPluginOptions = _ref.genVersionWebPluginOptions,
useFixMiniCssPlugin = _ref.useFixMiniCssPlugin,
_ref$aegisWebSdkExter = _ref.aegisWebSdkExternal,
aegisWebSdkExternal = _ref$aegisWebSdkExter === void 0 ? true : _ref$aegisWebSdkExter,
_ref$uniSimpleRouterE = _ref.uniSimpleRouterExternal,
uniSimpleRouterExternal = _ref$uniSimpleRouterE === void 0 ? false : _ref$uniSimpleRouterE,
_ref$axiosExternal = _ref.axiosExternal,
axiosExternal = _ref$axiosExternal === void 0 ? false : _ref$axiosExternal,
_ref$customPreload = _ref.customPreload,
customPreload = _ref$customPreload === void 0 ? false : _ref$customPreload,
_ref$usePMDBusinessAl = _ref.usePMDBusinessAlias,
usePMDBusinessAlias = _ref$usePMDBusinessAl === void 0 ? false : _ref$usePMDBusinessAl;
var transpileDependencies = DEFAULT_TRANSPILE_DEPENDENCIES;
var adapterDirs = DEFAULT_ADAPTER_DIRS;
var needSourceMap = getDefaultNeedSourceMap();
if (options !== null && options !== void 0 && options.adapterDirs) {
adapterDirs = options.adapterDirs || [];
}
if (options !== null && options !== void 0 && options.transpileDependencies) {
transpileDependencies = options.transpileDependencies;
}
if (typeof (options === null || options === void 0 ? void 0 : options.needSourceMap) === 'boolean') {
needSourceMap = options.needSourceMap;
}
var useH5SplitChunks = checkH5() && process.env.NODE_ENV === 'production' ? options === null || options === void 0 ? void 0 : options.useH5SplitChunks : false;
var optimization = {};
if (useH5SplitChunks) {
optimization.runtimeChunk = {
name: 'runtime'
};
}
if (checkDebugMode()) {
optimization.minimize = false;
}
return _objectSpread(_objectSpread({
parallel: process.env.NODE_ENV !== 'production',
lintOnSave: options.lintOnSave || false,
configureWebpack: _objectSpread({
resolve: {
alias: _objectSpread({}, getAllAppNameAlias(usePMDBusinessAlias))
},
externals: getExternals({
aegisWebSdkExternal: aegisWebSdkExternal,
uniSimpleRouterExternal: uniSimpleRouterExternal,
axiosExternal: axiosExternal,
vueLazyloadExternal: options.vueLazyloadExternal
}),
plugins: getPlugins({
adapterDirs: adapterDirs,
useDispatchScriptPlugin: useDispatchScriptPlugin,
dispatchScriptPluginOptions: dispatchScriptPluginOptions,
useDispatchVuePlugin: useDispatchVuePlugin,
dispatchVuePluginOptions: dispatchVuePluginOptions,
useCopyDirPlugin: useCopyDirPlugin,
copyDirPluginOptions: copyDirPluginOptions,
useAddPlaceHolderPlugin: useAddPlaceHolderPlugin,
remToRpxPluginMpOptions: remToRpxPluginMpOptions,
genVersionWebPluginOptions: genVersionWebPluginOptions,
useFixMiniCssPlugin: useFixMiniCssPlugin,
aegisWebSdkExternal: aegisWebSdkExternal,
uniSimpleRouterExternal: uniSimpleRouterExternal,
axiosExternal: axiosExternal,
vueLazyloadExternal: options.vueLazyloadExternal,
customPreload: customPreload,
useWorkBoxPlugin: options.useWorkBoxPlugin,
saveBundleAnalyzeHtml: options.saveBundleAnalyzeHtml,
useReplaceUniH5Plugin: options.useReplaceUniH5Plugin
}),
module: {
rules: [{
test: /\.(css)$/,
use: [LOADER_MAP.cssUrlBlankSpace]
}]
},
optimization: optimization
}, needSourceMap ? {
devtool: 'hidden-source-map'
} : {})
}, useH5SplitChunks ? {
pages: optimizationH5(useH5SplitChunks).pages
} : {}), {}, {
transpileDependencies: transpileDependencies,
chainWebpack: function chainWebpack$1(config) {
chainWebpack(config, options);
if (useH5SplitChunks) {
optimizationH5(useH5SplitChunks).chainWebpack(config);
}
}
});
}
exports.getUniVueConfig = getUniVueConfig;