UNPKG

uni-plugin-light

Version:

uni-app相关插件、loader及webpack基础配置

511 lines (500 loc) 18.9 kB
'use strict'; var path = require('path'); var utils = require('loader-utils'); var fs = require('fs'); var os = require('os'); var XRegExp = require('xregexp'); 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 path__namespace = /*#__PURE__*/_interopNamespace(path); var utils__default = /*#__PURE__*/_interopDefaultLegacy(utils); var fs__namespace = /*#__PURE__*/_interopNamespace(fs); var os__namespace = /*#__PURE__*/_interopNamespace(os); var XRegExp__namespace = /*#__PURE__*/_interopNamespace(XRegExp); 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); } var delim = { simple: { echo: '^#echo[ \t]+(.*?)[ \t]*$', exec: '^#exec[ \t]+(\\S+)[ \t]*\\((.*)\\)[ \t]*$', include: '^(.*)#include(?!-)[ \t]+(.*?)[ \t]*$', 'include-static': '^(.*)#include-static[ \t]+(.*?)[ \t]*$' }, html: { echo: '<!--[ \t]*#echo[ \t]+(.*?)[ \t]*(?:-->|!>)', exec: '<!--[ \t]*#exec[ \t]+(\\S+)[ \t]*\\((.*)\\)[ \t]*(?:-->|!>)', include: '(.*)<!--[ \t]*#include(?!-)[ \t]+(.*?)[ \t]*(?:-->|!>)', 'include-static': '(.*)<!--[ \t]*#include-static[ \t]+(.*?)[ \t]*(?:-->|!>)', exclude: { start: '[ \t]*<!--[ \t]*#exclude(?:[ \t]+(.*?))?[ \t]*(?:-->|!>)(?:[ \t]*\n+)?', end: '[ \t]*<!--[ \t]*#endexclude[ \t]*(?:-->|!>)(?:[ \t]*\n)?' }, extend: { start: '[ \t]*<!--[ \t]*#extend(?!able)[ \t]+(.*?)[ \t]*(?:-->|!>)(?:[ \t]*\n+)?', end: '[ \t]*<!--[ \t]*#endextend[ \t]*(?:-->|!>)(?:[ \t]*\n)?' }, extendable: '<!--[ \t]*#extendable[ \t]*(?:-->|!>)', "if": { start: '[ \t]*<!--[ \t]*#(ifndef|ifdef|if)[ \t]+(.*?)[ \t]*(?:-->|!>)(?:[ \t]*\n+)?', end: '[ \t]*<!(?:--)?[ \t]*#endif[ \t]*(?:-->|!>)(?:[ \t]*\n)?' }, foreach: { start: '[ \t]*<!--[ \t]*#foreach[ \t]+(.*?)[ \t]*(?:-->|!>)(?:[ \t]*\n+)?', end: '[ \t]*<!(?:--)?[ \t]*#endfor[ \t]*(?:-->|!>)(?:[ \t]*\n)?' } }, js: { echo: ['/\\*[ \t]*#echo[ \t]+(.*?)[ \t]*\\*(?:\\*|/)', '//[ \t]*#echo[ \t]+(.*?)[ \t]*$'], exec: '(?://|/\\*)[ \t]*#exec[ \t]+(\\S+)[ \t]*\\((.*)\\)[ \t]*(?:\\*(?:\\*|/))?', include: ['^(.*)/\\*[ \t]*#include(?!-)[ \t]+(.*?)[ \t]*\\*(?:\\*|/)', '^(.*)//[ \t]*#include(?!-)[ \t]+(.*?)[ \t]*$'], 'include-static': ['^(.*)/\\*[ \t]*#include-static[ \t]+(.*?)[ \t]*\\*(?:\\*|/)', '^(.*)//[ \t]*#include-static[ \t]+(.*?)[ \t]*$'], exclude: { start: '[ \t]*(?://|/\\*)[ \t]*#exclude(?:[ \t]+([^\n*]*))?[ \t]*(?:\\*(?:\\*|/))?(?:[ \t]*\n+)?', end: '[ \t]*(?://|/\\*)[ \t]*#endexclude[ \t]*(?:\\*(?:\\*|/))?(?:[ \t]*\n)?' }, extend: { start: '[ \t]*(?://|/\\*)[ \t]*#extend(?!able)[ \t]+([^\n*]*)(?:\\*(?:\\*|/))?(?:[ \t]*\n+)?', end: '[ \t]*(?://|/\\*)[ \t]*#endextend[ \t]*(?:\\*(?:\\*|/))?(?:[ \t]*\n)?' }, extendable: '[ \t]*(?://|/\\*)[ \t]*#extendable[ \t]*(?:\\*/)?', "if": { start: '[ \t]*(?://|/\\*)[ \t]*#(ifndef|ifdef|if)[ \t]+([^\n*]*)(?:\\*(?:\\*|/))?(?:[ \t]*\n+)?', end: '[ \t]*(?://|/\\*)[ \t]*#endif[ \t]*(?:\\*(?:\\*|/))?(?:[ \t]*\n)?' }, foreach: { start: '[ \t]*(?://|/\\*)[ \t]*#foreach[ \t]+([^\n*]*)(?:\\*(?:\\*|/))?(?:[ \t]*\n+)?', end: '[ \t]*(?://|/\\*)[ \t]*#endfor[ \t]*(?:\\*(?:\\*|/))?(?:[ \t]*\n)?' } }, coffee: { echo: '#+[ \t]*@echo[ \t]+(.*?)[ \t]*$', exec: '#+[ \t]*@exec[ \t]+(\\S+)[ \t]*\\((.*)\\)[ \t]*$', include: '^(.*?)#+[ \t]*@include(?!-)[ \t]+(.*?)[ \t]*$', 'include-static': '^(.*?)#+[ \t]*@include-static[ \t]+(.*?)[ \t]*$', exclude: { start: '^[ \t]*#+[ \t]*@exclude(?:[ \t]+(.*?))?[ \t]*\n+', end: '^[ \t]*#+[ \t]*@endexclude[ \t]*\n?' }, extend: { start: '^[ \t]*#+[ \t]*@extend(?!able)[ \t]+(.*?)\n+', end: '^[ \t]*#+[ \t]*@endextend[ \t]*\n?' }, extendable: '^[ \t]*#+[ \t]*@extendable[ \t]*$', "if": { start: '^[ \t]*#+[ \t]*@(ifndef|ifdef|if)[ \t]+(.*?)[ \t]*\n+', end: '^[ \t]*#+[ \t]*@endif[ \t]*\n?' }, foreach: { start: '^[ \t]*#+[ \t]*@foreach[ \t]+(.*?)[ \t]*\n+', end: '^[ \t]*#+[ \t]*@endfor[ \t]*\n?' } } }; delim.xml = delim.html; delim.javascript = delim.js; delim.jsx = delim.js; delim.c = delim.js; delim.cc = delim.js; delim.cpp = delim.js; delim.cs = delim.js; delim.csharp = delim.js; delim.java = delim.js; delim.less = delim.js; delim.sass = delim.js; delim.scss = delim.js; delim.css = delim.js; delim.php = delim.js; delim.ts = delim.js; delim.tsx = delim.js; delim.peg = delim.js; delim.pegjs = delim.js; delim.jade = delim.js; delim.styl = delim.js; delim.go = delim.js; delim.bash = delim.coffee; delim.shell = delim.coffee; delim.sh = delim.coffee; function preprocess(src, context, typeOrOptions) { src = src.toString(); context = context || process.env; // default values var options = { fileNotFoundSilentFail: false, srcDir: process.cwd(), srcEol: getEolType(src), type: delim.html }; // needed for backward compatibility with 2.x.x series if (typeof typeOrOptions === 'string') { typeOrOptions = { type: typeOrOptions }; } // needed for backward compatibility with 2.x.x series if (typeof context.srcDir === 'string') { typeOrOptions = typeOrOptions || {}; typeOrOptions.srcDir = context.srcDir; } if (typeOrOptions && _typeof(typeOrOptions) === 'object') { options.srcDir = typeOrOptions.srcDir || options.srcDir; options.fileNotFoundSilentFail = typeOrOptions.fileNotFoundSilentFail || options.fileNotFoundSilentFail; options.srcEol = typeOrOptions.srcEol || options.srcEol; options.type = delim[typeOrOptions.type] || options.type; } context = copy(context); return preprocessor(src, context, options); } function preprocessor(src, context, opts) { var noRestoreEol = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; src = normalizeEol(src); var rv = src; rv = replace(rv, opts.type.include, processIncludeDirective.bind(null, false, context, opts)); if (opts.type.extend) { rv = replaceRecursive(rv, opts.type.extend, function (startMatches, endMatches, include, recurse) { var file = (startMatches[1] || '').trim(); var extendedContext = copy(context); var extendedOpts = copy(opts); extendedContext.src = path__namespace.join(opts.srcDir, file); extendedOpts.srcDir = path__namespace.dirname(extendedContext.src); var fileContents = getFileContents(extendedContext.src, opts.fileNotFoundSilentFail, context.src); if (fileContents.error) { return fileContents.contents; } var extendedSource = preprocessor(fileContents.contents, extendedContext, extendedOpts, true).trim(); if (extendedSource) { include = include.replace(/^\n?|\n?$/g, ''); return replace(extendedSource, opts.type.extendable, recurse(include)); } return ''; }); } if (opts.type.foreach) { rv = replaceRecursive(rv, opts.type.foreach, function (startMatches, endMatches, include, recurse) { var variable = (startMatches[1] || '').trim(); var forParams = variable.split(' '); if (forParams.length === 3) { var contextVar = forParams[2]; var arrString = getDeepPropFromObj(context, contextVar); var eachArr; if (arrString.match(/\{(.*)\}/)) { eachArr = JSON.parse(arrString); } else if (arrString.match(/\[(.*)\]/)) { eachArr = arrString.slice(1, -1); eachArr = eachArr.split(','); eachArr = eachArr.map(function (arrEntry) { return arrEntry.replace(/\s*(['"])(.*)\1\s*/, '$2'); }); } else { eachArr = arrString.split(','); } var replaceToken = new RegExp(XRegExp__namespace.escape(forParams[0]), 'g'); var recursedInclude = recurse(include); return Object.keys(eachArr).reduce(function (stringBuilder, arrKey) { var arrEntry = eachArr[arrKey]; return stringBuilder + recursedInclude.replace(replaceToken, arrEntry); }, ''); } return ''; }); } if (opts.type.exclude) { rv = replaceRecursive(rv, opts.type.exclude, function (startMatches, endMatches, include, recurse) { var test = (startMatches[1] || '').trim(); return testPasses(test, context) ? '' : recurse(include); }); } if (opts.type["if"]) { rv = replaceRecursive(rv, opts.type["if"], function (startMatches, endMatches, include, recurse) { var variant = startMatches[1]; var test = (startMatches[2] || '').trim(); switch (variant) { case 'if': case 'ifdef': return testPasses(test, context) ? padContent(startMatches.input) + recurse(include) + padContent(endMatches.input) : padContent(startMatches.input + include + endMatches.input); case 'ifndef': return !testPasses(test, context) ? padContent(startMatches.input) + recurse(include) + padContent(endMatches.input) : padContent(startMatches.input + include + endMatches.input); // case 'ifdef': // return typeof getDeepPropFromObj(context, test) !== 'undefined' // ? (padContent(startMatches.input) + recurse(include) + padContent(endMatches.input)) // : padContent(startMatches.input + include + endMatches.input) // fixed by xxxxxx // case 'ifndef': // return typeof getDeepPropFromObj(context, test) === 'undefined' // ? (padContent(startMatches.input) + recurse(include) + padContent(endMatches.input)) // : padContent(startMatches.input + include + endMatches.input) // fixed by xxxxxx default: throw new Error("Unknown if variant ".concat(variant, ".")); } }); } rv = replace(rv, opts.type.echo, function (match, variable) { variable = (variable || '').trim(); // if we are surrounded by quotes, echo as a string var stringMatch = variable.match(/^(['"])(.*)\1$/); if (stringMatch) return stringMatch[2]; return getDeepPropFromObj(context, (variable || '').trim()); }); rv = replace(rv, opts.type.exec, function (match, name, value) { name = (name || '').trim(); value = value || ''; var params = value.split(','); var stringRegex = /^['"](.*)['"]$/; params = params.map(function (param) { param = param.trim(); if (stringRegex.test(param)) { // handle string parameter return param.replace(stringRegex, '$1'); } // handle variable parameter return getDeepPropFromObj(context, param); }); var fn = getDeepPropFromObj(context, name); if (!fn || typeof fn !== 'function') return ''; return fn.apply(context, params); }); rv = replace(rv, opts.type['include-static'], processIncludeDirective.bind(null, true, context, opts)); if (!noRestoreEol) { rv = restoreEol(rv, opts.srcEol); } return rv; } var splitRE = /\r?\n/g; function padContent(content) { return Array(content.split(splitRE).length).join('\n'); } function getEolType(source) { var eol; var foundEolTypeCnt = 0; if (source.indexOf('\r\n') >= 0) { eol = '\r\n'; foundEolTypeCnt += 1; } if (/\r[^\n]/.test(source)) { eol = '\r'; foundEolTypeCnt += 1; } if (/[^\r]\n/.test(source)) { eol = '\n'; foundEolTypeCnt += 1; } if (eol == null || foundEolTypeCnt > 1) { eol = os__namespace.EOL; } return eol; } function normalizeEol(source) { var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; // only process any kind of EOL if indentation has to be added, otherwise replace only non \n EOLs if (indent) { source = source.replace(/(?:\r?\n)|\r/g, "\n".concat(indent)); } else { source = source.replace(/(?:\r\n)|\r/g, '\n'); } return source; } function restoreEol(normalizedSource, originalEol) { if (originalEol !== '\n') { normalizedSource = normalizedSource.replace(/\n/g, originalEol); } return normalizedSource; } function replace(rv, rule, processor) { var isRegex = typeof rule === 'string' || rule instanceof RegExp; var isArray = Array.isArray(rule); if (isRegex) { rule = [new RegExp(rule, 'gmi')]; } else if (isArray) { rule = rule.map(function (subRule) { return new RegExp(subRule, 'gmi'); }); } else { throw new Error('Rule must be a String, a RegExp, or an Array.'); } return rule.reduce(function (rv, rule) { return rv.replace(rule, processor); }, rv); } function replaceRecursive(rv, rule, processor) { if (!rule.start || !rule.end) { throw new Error('Recursive rule must have start and end.'); } var startRegex = new RegExp(rule.start, 'mi'); var endRegex = new RegExp(rule.end, 'mi'); function matchReplacePass(content) { var matches = XRegExp__namespace.matchRecursive(content, rule.start, rule.end, 'gmi', { valueNames: ['between', 'left', 'match', 'right'] }); var matchGroup = { left: null, match: null, right: null }; return matches.reduce(function (builder, match) { switch (match.name) { case 'between': builder += match.value; break; case 'left': matchGroup.left = startRegex.exec(match.value); break; case 'match': matchGroup.match = match.value; break; case 'right': matchGroup.right = endRegex.exec(match.value); builder += processor(matchGroup.left, matchGroup.right, matchGroup.match, matchReplacePass); break; } return builder; }, ''); } return matchReplacePass(rv); } function processIncludeDirective(isStatic, context, opts, match, linePrefix, file) { file = (file || '').trim(); var indent = linePrefix.replace(/\S/g, ' '); var includedContext = copy(context); var includedOpts = copy(opts); includedContext.src = path__namespace.join(opts.srcDir, file); includedOpts.srcDir = path__namespace.dirname(includedContext.src); var fileContents = getFileContents(includedContext.src, opts.fileNotFoundSilentFail, context.src); if (fileContents.error) { return linePrefix + fileContents.contents; } var includedSource = fileContents.contents; if (isStatic) { includedSource = fileContents.contents; } else { includedSource = preprocessor(fileContents.contents, includedContext, includedOpts, true); } includedSource = normalizeEol(includedSource, indent); if (includedSource) { return linePrefix + includedSource; } return linePrefix; } function getTestTemplate(test) { /* jshint evil:true */ test = test || 'true'; test = test.trim(); // force single equals replacement test = test.replace(/([^=!])=([^=])/g, '$1==$2'); // fixed by xxxxxx test = test.replace(/-/g, '_'); /* eslint-disable no-new-func */ return new Function('context', "with (context||{}){ return ( ".concat(test, " ); }")); } function testPasses(test, context) { var testFn = getTestTemplate(test); try { return testFn(context, getDeepPropFromObj); } catch (e) {} return false; } function getFileContents(path, failSilent, requesterPath) { try { fs__namespace.statSync(path); } catch (e) { if (failSilent) { return { error: true, contents: "".concat(path, " not found!") }; } var errMsg = path; errMsg = requesterPath ? "".concat(errMsg, " requested from ").concat(requesterPath) : errMsg; errMsg += ' not found!'; throw new Error(errMsg); } return { error: false, contents: fs__namespace.readFileSync(path).toString() }; } function copy(obj) { return Object.keys(obj).reduce(function (copyObj, objKey) { copyObj[objKey] = obj[objKey]; return copyObj; }, {}); } function getDeepPropFromObj(obj, propPath) { propPath.replace(/\[([^\]+?])\]/g, '.$1'); propPath = propPath.split('.'); // fast path, no need to loop if structurePath contains only a single segment if (propPath.length === 1) { return obj[propPath[0]]; } // loop only as long as possible (no exceptions for null/undefined property access) propPath.some(function (pathSegment) { obj = obj[pathSegment]; return obj == null; }); return obj; } var ERRORS = { html: "\u6761\u4EF6\u7F16\u8BD1\u5931\u8D25,\u53C2\u8003\u793A\u4F8B(\u6CE8\u610F ifdef \u4E0E endif \u5FC5\u987B\u914D\u5BF9\u4F7F\u7528):\n<!-- #ifdef %PLATFORM% -->\n\u6A21\u677F\u4EE3\u7801\n<!-- #endif -->\n", js: "\u6761\u4EF6\u7F16\u8BD1\u5931\u8D25,\u53C2\u8003\u793A\u4F8B(\u6CE8\u610F ifdef \u4E0E endif \u5FC5\u987B\u914D\u5BF9\u4F7F\u7528):\n// #ifdef %PLATFORM%\njs\u4EE3\u7801\n// #endif\n", css: "\u6761\u4EF6\u7F16\u8BD1\u5931\u8D25,\u53C2\u8003\u793A\u4F8B(\u6CE8\u610F ifdef \u4E0E endif \u5FC5\u987B\u914D\u5BF9\u4F7F\u7528):\n/* #ifdef %PLATFORM% */\ncss\u4EE3\u7801\n/* #endif */\n" }; var TAGS = { html: 'template', js: 'script', css: 'style' }; function preprocessLoader() { var content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; if (content.indexOf('#ifdef') < 0 && content.indexOf('#ifndef') < 0) { return content; } // @ts-ignore var _utils$getOptions = utils__default["default"].getOptions(this), type = _utils$getOptions.type, _utils$getOptions$con = _utils$getOptions.context, context = _utils$getOptions$con === void 0 ? {} : _utils$getOptions$con, _utils$getOptions$log = _utils$getOptions.log, log = _utils$getOptions$log === void 0 ? false : _utils$getOptions$log; var types = type; if (!Array.isArray(types)) { types = [types]; } // @ts-ignore var resourcePath = this.resourcePath; if (log) { console.log('[ifdef-loader]正在处理: ', resourcePath); } types.forEach(function (type) { try { content = preprocess(content, context, { type: type }); } catch (e) { if (~['.nvue', '.vue'].indexOf(path__namespace.extname(resourcePath))) { console.error("".concat(TAGS[type], "\u8282\u70B9 ").concat(ERRORS[type])); } else { console.error("".concat(ERRORS[type])); } } }); return content; } module.exports = preprocessLoader;