xhs-mp-compiler-cli 1.0.2-beta.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/bin/xhs-mp-cli-build.d.ts +2 -0
  2. package/dist/bin/xhs-mp-cli-build.js +40 -0
  3. package/dist/bin/xhs-mp-cli-dev.d.ts +2 -0
  4. package/dist/bin/xhs-mp-cli-dev.js +81 -0
  5. package/dist/bin/xhs-mp-cli.d.ts +2 -0
  6. package/dist/bin/xhs-mp-cli.js +16 -0
  7. package/dist/build/index.d.ts +3 -0
  8. package/dist/build/index.js +22 -0
  9. package/dist/dev-server/index.d.ts +3 -0
  10. package/dist/dev-server/index.js +62 -0
  11. package/dist/dev-server/lib/ensurePort.d.ts +2 -0
  12. package/dist/dev-server/lib/ensurePort.js +32 -0
  13. package/dist/dev-server/lib/openBrowser.d.ts +2 -0
  14. package/dist/dev-server/lib/openBrowser.js +23 -0
  15. package/dist/dev-server/lib/openChrome.applescript +78 -0
  16. package/dist/globalData/SjsModule.d.ts +32 -0
  17. package/dist/globalData/SjsModule.js +34 -0
  18. package/dist/index.d.ts +11 -0
  19. package/dist/index.js +114 -0
  20. package/dist/types/index.d.ts +106 -0
  21. package/dist/types/index.js +13 -0
  22. package/dist/utils/asyncWebpack.d.ts +3 -0
  23. package/dist/utils/asyncWebpack.js +38 -0
  24. package/dist/utils/combineExtJson.d.ts +3 -0
  25. package/dist/utils/combineExtJson.js +74 -0
  26. package/dist/utils/common.d.ts +7 -0
  27. package/dist/utils/common.js +35 -0
  28. package/dist/utils/depenedHelper.d.ts +31 -0
  29. package/dist/utils/depenedHelper.js +89 -0
  30. package/dist/utils/getCssSuffixName.d.ts +1 -0
  31. package/dist/utils/getCssSuffixName.js +9 -0
  32. package/dist/utils/getMlSuffixName.d.ts +1 -0
  33. package/dist/utils/getMlSuffixName.js +6 -0
  34. package/dist/utils/getPrefixName.d.ts +1 -0
  35. package/dist/utils/getPrefixName.js +6 -0
  36. package/dist/utils/projectConfig.d.ts +1 -0
  37. package/dist/utils/projectConfig.js +20 -0
  38. package/dist/utils/transformAppJson.d.ts +16 -0
  39. package/dist/utils/transformAppJson.js +199 -0
  40. package/dist/utils/validateAppJson.d.ts +4 -0
  41. package/dist/utils/validateAppJson.js +111 -0
  42. package/dist/webpack-config/index.d.ts +4 -0
  43. package/dist/webpack-config/index.js +41 -0
  44. package/dist/webpack-config/lib/const.d.ts +13 -0
  45. package/dist/webpack-config/lib/const.js +15 -0
  46. package/dist/webpack-config/lib/css.d.ts +2 -0
  47. package/dist/webpack-config/lib/css.js +41 -0
  48. package/dist/webpack-config/lib/postcssRpx2Vw.d.ts +12 -0
  49. package/dist/webpack-config/lib/postcssRpx2Vw.js +35 -0
  50. package/dist/webpack-config/lib/tagTransformMap.d.ts +35 -0
  51. package/dist/webpack-config/lib/tagTransformMap.js +38 -0
  52. package/dist/webpack-config/lib/utils.d.ts +5 -0
  53. package/dist/webpack-config/lib/utils.js +37 -0
  54. package/dist/webpack-config/loaders/component-entry-loader.d.ts +1 -0
  55. package/dist/webpack-config/loaders/component-entry-loader.js +31 -0
  56. package/dist/webpack-config/loaders/component-entry-requirements-loader.d.ts +1 -0
  57. package/dist/webpack-config/loaders/component-entry-requirements-loader.js +24 -0
  58. package/dist/webpack-config/loaders/mini-style-loader.d.ts +1 -0
  59. package/dist/webpack-config/loaders/mini-style-loader.js +69 -0
  60. package/dist/webpack-config/loaders/render-entry-loader.d.ts +1 -0
  61. package/dist/webpack-config/loaders/render-entry-loader.js +50 -0
  62. package/dist/webpack-config/loaders/service-entry-loader.d.ts +1 -0
  63. package/dist/webpack-config/loaders/service-entry-loader.js +51 -0
  64. package/dist/webpack-config/loaders/sjs-loader/index.d.ts +12 -0
  65. package/dist/webpack-config/loaders/sjs-loader/index.js +609 -0
  66. package/dist/webpack-config/loaders/sjs-loader/scope.d.ts +36 -0
  67. package/dist/webpack-config/loaders/sjs-loader/scope.js +122 -0
  68. package/dist/webpack-config/loaders/sjs-loader/tranform.d.ts +2 -0
  69. package/dist/webpack-config/loaders/sjs-loader/tranform.js +31 -0
  70. package/dist/webpack-config/loaders/utils.d.ts +13 -0
  71. package/dist/webpack-config/loaders/utils.js +41 -0
  72. package/dist/webpack-config/loaders/wxss-loader.d.ts +1 -0
  73. package/dist/webpack-config/loaders/wxss-loader.js +76 -0
  74. package/dist/webpack-config/plugins/VueLoaderPlugin.d.ts +19 -0
  75. package/dist/webpack-config/plugins/VueLoaderPlugin.js +205 -0
  76. package/dist/webpack-config/plugins/XhsMpErrorTransformPlugin.d.ts +8 -0
  77. package/dist/webpack-config/plugins/XhsMpErrorTransformPlugin.js +40 -0
  78. package/dist/webpack-config/plugins/XhsMpJsonPlugin.d.ts +36 -0
  79. package/dist/webpack-config/plugins/XhsMpJsonPlugin.js +71 -0
  80. package/dist/webpack-config/presets/babel.d.ts +8 -0
  81. package/dist/webpack-config/presets/babel.js +57 -0
  82. package/dist/webpack-config/presets/common.d.ts +4 -0
  83. package/dist/webpack-config/presets/common.js +40 -0
  84. package/dist/webpack-config/presets/mp/MpEntryPlugin.d.ts +23 -0
  85. package/dist/webpack-config/presets/mp/MpEntryPlugin.js +87 -0
  86. package/dist/webpack-config/presets/mp/index.d.ts +4 -0
  87. package/dist/webpack-config/presets/mp/index.js +48 -0
  88. package/dist/webpack-config/presets/prod.d.ts +4 -0
  89. package/dist/webpack-config/presets/prod.js +83 -0
  90. package/dist/webpack-config/presets/render/ComponentEntryPlugin.d.ts +18 -0
  91. package/dist/webpack-config/presets/render/ComponentEntryPlugin.js +77 -0
  92. package/dist/webpack-config/presets/render/RenderChunkPlugin.d.ts +5 -0
  93. package/dist/webpack-config/presets/render/RenderChunkPlugin.js +50 -0
  94. package/dist/webpack-config/presets/render/RenderEntryPlugin.d.ts +14 -0
  95. package/dist/webpack-config/presets/render/RenderEntryPlugin.js +42 -0
  96. package/dist/webpack-config/presets/render/SjsEntryPlugin.d.ts +31 -0
  97. package/dist/webpack-config/presets/render/SjsEntryPlugin.js +160 -0
  98. package/dist/webpack-config/presets/render/index.d.ts +4 -0
  99. package/dist/webpack-config/presets/render/index.js +62 -0
  100. package/dist/webpack-config/presets/service/ServiceEntryPlugin.d.ts +8 -0
  101. package/dist/webpack-config/presets/service/ServiceEntryPlugin.js +36 -0
  102. package/dist/webpack-config/presets/service/XhsMpServiceChunkPlugin.d.ts +6 -0
  103. package/dist/webpack-config/presets/service/XhsMpServiceChunkPlugin.js +46 -0
  104. package/dist/webpack-config/presets/service/XhsResolveLimitPlugin.d.ts +8 -0
  105. package/dist/webpack-config/presets/service/XhsResolveLimitPlugin.js +65 -0
  106. package/dist/webpack-config/presets/service/XhsV2AssetsPlugin.d.ts +5 -0
  107. package/dist/webpack-config/presets/service/XhsV2AssetsPlugin.js +27 -0
  108. package/dist/webpack-config/presets/service/index.d.ts +4 -0
  109. package/dist/webpack-config/presets/service/index.js +39 -0
  110. package/package.json +2 -2
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ScopeManager = exports.Scope = exports.SPECIFY_VAR = void 0;
4
+ exports.SPECIFY_VAR = ["getDate", "getRegExp", "console"];
5
+ const IDENTIFIER_WHITE_LIST = [
6
+ "Object", "Boolean", "Array", "String", "Number", "Date", "Map", "Set",
7
+ "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "isNaN", "isFinite", "parseFloat", "parseInt",
8
+ "Infinity", "NaN", "undefined",
9
+ "setTimeout", "clearTimeout", "setInterval", "clearInterval",
10
+ "JSON", "Math",
11
+ // 模块化
12
+ "module", "require", "exports",
13
+ ...exports.SPECIFY_VAR
14
+ ];
15
+ // 变量作用域表
16
+ class Scope {
17
+ constructor() {
18
+ // 当前作用域定义的变量
19
+ this.defines = {};
20
+ // 当前作用域使用的变量
21
+ this.access = {};
22
+ }
23
+ toString() {
24
+ return `defines: ${Object.keys(this.defines)} access: ${Object.keys(this.access)}`;
25
+ }
26
+ /**
27
+ * @returns
28
+ */
29
+ anlysis() {
30
+ // TODO 优化算法复杂度
31
+ // 在自身作用域 以及 上级作用域寻找,找到顶层作用域时 则需要看 白名单是否含有
32
+ for (const variable in this.access) {
33
+ // 白名单也不包含此变量
34
+ if (this.checkGlobal(variable) && !IDENTIFIER_WHITE_LIST.includes(variable)) {
35
+ return { variable, span: this.access[variable] };
36
+ }
37
+ }
38
+ return undefined;
39
+ }
40
+ // 检查是否是全局调用
41
+ checkGlobal(key) {
42
+ let scope = this;
43
+ while (scope) {
44
+ if (!scope.defines[key]) {
45
+ scope = scope.parentScope;
46
+ continue;
47
+ }
48
+ else {
49
+ return false;
50
+ }
51
+ }
52
+ return !scope;
53
+ }
54
+ setAccess(key, value) {
55
+ this.access[key] = value;
56
+ }
57
+ setDefines(key, value) {
58
+ this.defines[key] = value;
59
+ }
60
+ setParentScope(scope) {
61
+ this.parentScope = scope;
62
+ }
63
+ }
64
+ exports.Scope = Scope;
65
+ class ScopeManager {
66
+ constructor() {
67
+ // 栈帧
68
+ this._scopeStack = [];
69
+ // 栈 深度遍历结果
70
+ this._scopeTables = [];
71
+ // 是否停止收集
72
+ this._stop = false;
73
+ }
74
+ // 停止分析
75
+ stop() {
76
+ this._stop = true;
77
+ }
78
+ enterScope() {
79
+ if (this._stop)
80
+ return;
81
+ this._scopeStack.push(new Scope());
82
+ }
83
+ exitScope() {
84
+ if (this._stop)
85
+ return;
86
+ const scope = this._scopeStack.pop();
87
+ if (scope) {
88
+ this._scopeTables.push(scope);
89
+ scope.setParentScope(this.getCurrentScope());
90
+ }
91
+ }
92
+ getCurrentScope() {
93
+ if (this._stop)
94
+ return;
95
+ return this._scopeStack[this._scopeStack.length - 1];
96
+ }
97
+ // 记录定义的值
98
+ pushIdentifier(id) {
99
+ var _a;
100
+ if (this._stop)
101
+ return;
102
+ if (this.getCurrentScope()) {
103
+ (_a = this.getCurrentScope()) === null || _a === void 0 ? void 0 : _a.setDefines(id.value, id.span);
104
+ }
105
+ }
106
+ // 记录使用的值
107
+ pushAccess(id) {
108
+ if (this._stop)
109
+ return;
110
+ const current = this.getCurrentScope();
111
+ if (current) {
112
+ current === null || current === void 0 ? void 0 : current.setAccess(id.value, id.span);
113
+ if (exports.SPECIFY_VAR.includes(id.value)) {
114
+ id._xhsScope = current;
115
+ }
116
+ }
117
+ }
118
+ getDFSScope() {
119
+ return this._scopeTables;
120
+ }
121
+ }
122
+ exports.ScopeManager = ScopeManager;
@@ -0,0 +1,2 @@
1
+ import type { JscTarget, Program } from '@swc/core';
2
+ export declare const transform: (code: string, plugin?: ((m: Program) => Program) | undefined, target?: JscTarget, minify?: boolean) => import("@swc/core").Output;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transform = void 0;
4
+ const core_1 = require("@swc/core");
5
+ const transform = (code, plugin, target = 'esnext', minify = false) => (0, core_1.transformSync)(code, {
6
+ swcrc: false,
7
+ configFile: false,
8
+ minify,
9
+ sourceMaps: false,
10
+ jsc: {
11
+ preserveAllComments: true,
12
+ target,
13
+ // minify: false,
14
+ externalHelpers: false,
15
+ parser: {
16
+ syntax: "ecmascript",
17
+ jsx: false,
18
+ dynamicImport: false,
19
+ privateMethod: false,
20
+ functionBind: false,
21
+ classPrivateProperty: false,
22
+ exportDefaultFrom: false,
23
+ exportNamespaceFrom: false,
24
+ decorators: false,
25
+ decoratorsBeforeExport: false,
26
+ importMeta: false,
27
+ },
28
+ },
29
+ plugin,
30
+ });
31
+ exports.transform = transform;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * 根据是否分包获取资源路径
3
+ */
4
+ export declare const getResourceUris: (options: {
5
+ appCssExist: boolean;
6
+ enableLazyCodeLoading: boolean;
7
+ subPackage: any;
8
+ }) => string[];
9
+ /**
10
+ * @NOTE
11
+ * Create a request and handle the conversion of esModule modules
12
+ * */
13
+ export declare function createRequire(modulePath: string): string;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRequire = exports.getResourceUris = void 0;
4
+ /**
5
+ * 根据是否分包获取资源路径
6
+ */
7
+ const getResourceUris = (options) => {
8
+ const resourceList = [];
9
+ const { appCssExist, enableLazyCodeLoading, subPackage } = options;
10
+ // sjs 无法识别是否引用 所以一律push
11
+ // 加载顺序 app.css 主包sjs 分包sjs 主包components.js 分包components.js
12
+ if (!subPackage) {
13
+ // 主包
14
+ appCssExist && resourceList.push(`app.css`);
15
+ resourceList.push('sjs.js');
16
+ !enableLazyCodeLoading && resourceList.push(`components.js`);
17
+ }
18
+ else if (subPackage === null || subPackage === void 0 ? void 0 : subPackage.independent) {
19
+ // 独立分包, 自己的components.js
20
+ resourceList.push(`${subPackage === null || subPackage === void 0 ? void 0 : subPackage.root}/sjs.js`);
21
+ !enableLazyCodeLoading && resourceList.push(`${subPackage === null || subPackage === void 0 ? void 0 : subPackage.root}/components.js`);
22
+ }
23
+ else if (subPackage) {
24
+ // 普通分包, 自己的components.js,主包components.js app.css
25
+ appCssExist && resourceList.push(`app.css`);
26
+ resourceList.push('sjs.js');
27
+ resourceList.push(`${subPackage === null || subPackage === void 0 ? void 0 : subPackage.root}/sjs.js`);
28
+ !enableLazyCodeLoading && resourceList.push(`components.js`);
29
+ !enableLazyCodeLoading && resourceList.push(`${subPackage === null || subPackage === void 0 ? void 0 : subPackage.root}/components.js`);
30
+ }
31
+ return resourceList;
32
+ };
33
+ exports.getResourceUris = getResourceUris;
34
+ /**
35
+ * @NOTE
36
+ * Create a request and handle the conversion of esModule modules
37
+ * */
38
+ function createRequire(modulePath) {
39
+ return `function() { var obj = require('${modulePath}'); return obj && obj.__esModule ? obj.default : obj; }`;
40
+ }
41
+ exports.createRequire = createRequire;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const postcss_1 = __importDefault(require("postcss"));
16
+ const postcss_import_1 = __importDefault(require("postcss-import"));
17
+ const postcss_prefix_selector_1 = __importDefault(require("postcss-prefix-selector"));
18
+ const CssSyntaxError_1 = __importDefault(require("css-loader/dist/CssSyntaxError"));
19
+ const tagTransformMap_1 = __importDefault(require("../lib/tagTransformMap"));
20
+ const getCssSuffixName_1 = __importDefault(require("../../utils/getCssSuffixName"));
21
+ const common_1 = require("../../utils/common");
22
+ const tags = Object.keys(tagTransformMap_1.default).join('|');
23
+ const labelStr = `(^|\\s)(${tags}|page|audio|live-player|map|cover-view|cover-image|video)`;
24
+ const labelReg = new RegExp(labelStr, 'g');
25
+ function wxssLoader(source) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ var _a, _b, _c, _d, _e;
28
+ const done = this.async();
29
+ this._compiler.xhsData = this._compiler.xhsData || {};
30
+ const { appJSON = {}, miniprogramDir = '' } = this._compiler.xhsData;
31
+ const shortPath = (0, common_1.getShortPath)(miniprogramDir, this.resourcePath).replace(new RegExp(`\\.${(0, getCssSuffixName_1.default)()}$`), '');
32
+ const index = (_c = (_b = (_a = appJSON === null || appJSON === void 0 ? void 0 : appJSON.componentsMap) === null || _a === void 0 ? void 0 : _a[shortPath]) === null || _b === void 0 ? void 0 : _b.index) !== null && _c !== void 0 ? _c : null;
33
+ const styleIsolation = (_e = (_d = appJSON === null || appJSON === void 0 ? void 0 : appJSON.componentsMap) === null || _d === void 0 ? void 0 : _d[shortPath]) === null || _e === void 0 ? void 0 : _e.styleIsolation;
34
+ const selectorIndex = styleIsolation === 'shared' ? 0 : index || 0;
35
+ // js / json 的配置会影响样式
36
+ const extReg = new RegExp(`${(0, getCssSuffixName_1.default)()}$`);
37
+ this.addDependency(this.resourcePath.replace(extReg, 'js'));
38
+ this.addDependency(this.resourcePath.replace(extReg, 'json'));
39
+ (0, postcss_1.default)()
40
+ .use((0, postcss_import_1.default)({ root: miniprogramDir }))
41
+ .use((0, postcss_prefix_selector_1.default)({
42
+ prefix: 'xhs',
43
+ transform(prefix, selector) {
44
+ // 支持 host 选择器 https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
45
+ if (selector === ':host') {
46
+ return `[is="${shortPath}"]`;
47
+ }
48
+ /**
49
+ * 替换所有类选择器,用于做样式隔离 wiki: https://wiki.xiaohongshu.com/pages/viewpage.action?pageId=181017177
50
+ * .app -> .xhs_0_app
51
+ */
52
+ selector = selector.replace(/\.(\w)/g, `.xhs_${selectorIndex}_$1`);
53
+ // 为内置组件加上 xhs 前缀
54
+ if (selector.match(labelReg)) {
55
+ selector = selector.replace(labelReg, `$1${prefix}-$2`);
56
+ }
57
+ return selector;
58
+ },
59
+ }))
60
+ .process(source, {
61
+ from: this.resourcePath,
62
+ })
63
+ .then(result => {
64
+ result.messages.forEach(({ file, type }) => {
65
+ if (type === 'dependency') {
66
+ this.addDependency(file);
67
+ }
68
+ });
69
+ done(null, result.css);
70
+ })
71
+ .catch(error => {
72
+ done(error.name === 'CssSyntaxError' ? new CssSyntaxError_1.default(error) : error);
73
+ });
74
+ });
75
+ }
76
+ module.exports = wxssLoader;
@@ -0,0 +1,19 @@
1
+ import { TemplateCompiler, CompilerOptions, SFCTemplateCompileOptions, SFCScriptCompileOptions } from 'vue/compiler-sfc';
2
+ import { Compiler, Plugin } from 'webpack';
3
+ export interface VueLoaderOptions {
4
+ babelParserPlugins?: SFCScriptCompileOptions['babelParserPlugins'];
5
+ transformAssetUrls?: SFCTemplateCompileOptions['transformAssetUrls'];
6
+ compiler?: TemplateCompiler | string;
7
+ compilerOptions?: CompilerOptions;
8
+ refSugar?: boolean;
9
+ customElement?: boolean | RegExp;
10
+ hotReload?: boolean;
11
+ exposeFilename?: boolean;
12
+ appendExtension?: boolean;
13
+ isServerBuild?: boolean;
14
+ }
15
+ declare class VueLoaderPlugin implements Plugin {
16
+ static NS: string;
17
+ apply(compiler: Compiler): void;
18
+ }
19
+ export default VueLoaderPlugin;
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
7
+ // @ts-nocheck
8
+ const querystring_1 = __importDefault(require("querystring"));
9
+ const getMlSuffixName_1 = __importDefault(require("../../utils/getMlSuffixName"));
10
+ const id = 'vue-loader-plugin';
11
+ const NS = 'vue-loader';
12
+ const NormalModule = require('webpack/lib/NormalModule');
13
+ const BasicEffectRulePlugin = require('webpack/lib/rules/BasicEffectRulePlugin');
14
+ const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin');
15
+ const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin');
16
+ const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler');
17
+ const ObjectMatcherRulePlugin = require('webpack/lib/rules/ObjectMatcherRulePlugin');
18
+ const objectMatcherRulePlugins = [];
19
+ objectMatcherRulePlugins.push(new ObjectMatcherRulePlugin('assert', 'assertions'), new ObjectMatcherRulePlugin('descriptionData'));
20
+ const ruleSetCompiler = new RuleSetCompiler([
21
+ new BasicMatcherRulePlugin('test', 'resource'),
22
+ new BasicMatcherRulePlugin('mimetype'),
23
+ new BasicMatcherRulePlugin('dependency'),
24
+ new BasicMatcherRulePlugin('include', 'resource'),
25
+ new BasicMatcherRulePlugin('exclude', 'resource', true),
26
+ new BasicMatcherRulePlugin('conditions'),
27
+ new BasicMatcherRulePlugin('resource'),
28
+ new BasicMatcherRulePlugin('resourceQuery'),
29
+ new BasicMatcherRulePlugin('resourceFragment'),
30
+ new BasicMatcherRulePlugin('realResource'),
31
+ new BasicMatcherRulePlugin('issuer'),
32
+ new BasicMatcherRulePlugin('compiler'),
33
+ ...objectMatcherRulePlugins,
34
+ new BasicEffectRulePlugin('type'),
35
+ new BasicEffectRulePlugin('sideEffects'),
36
+ new BasicEffectRulePlugin('parser'),
37
+ new BasicEffectRulePlugin('resolve'),
38
+ new BasicEffectRulePlugin('generator'),
39
+ new UseEffectRulePlugin(),
40
+ ]);
41
+ let uid = 0;
42
+ const matcherCache = new WeakMap();
43
+ function match(rule, fakeFile) {
44
+ let ruleSet = matcherCache.get(rule);
45
+ if (!ruleSet) {
46
+ // skip the `include` check when locating the vue rule
47
+ const clonedRawRule = Object.assign({}, rule);
48
+ delete clonedRawRule.include;
49
+ ruleSet = ruleSetCompiler.compile([clonedRawRule]);
50
+ matcherCache.set(rule, ruleSet);
51
+ }
52
+ return ruleSet.exec({
53
+ resource: fakeFile,
54
+ });
55
+ }
56
+ function cloneRule(rawRule, refs, ruleCheck, ruleResource) {
57
+ const compiledRule = ruleSetCompiler.compileRule(`clonedRuleSet-${++uid}`, rawRule, refs);
58
+ // do not process rule with enforce
59
+ if (!rawRule.enforce) {
60
+ const ruleUse = compiledRule.effects
61
+ .filter(effect => effect.type === 'use')
62
+ .map((effect) => effect.value);
63
+ // fix conflict with config.loader and config.options when using config.use
64
+ delete rawRule.loader;
65
+ delete rawRule.options;
66
+ rawRule.use = ruleUse;
67
+ }
68
+ let currentResource;
69
+ const res = Object.assign(Object.assign({}, rawRule), { resource: (resources) => {
70
+ currentResource = resources;
71
+ return true;
72
+ }, resourceQuery: (query) => {
73
+ if (!query) {
74
+ return false;
75
+ }
76
+ const parsed = querystring_1.default.parse(query.slice(1));
77
+ if (parsed.vue == null) {
78
+ return false;
79
+ }
80
+ if (!ruleCheck(parsed, compiledRule)) {
81
+ return false;
82
+ }
83
+ const fakeResourcePath = ruleResource(parsed, currentResource);
84
+ for (const condition of compiledRule.conditions) {
85
+ // add support for resourceQuery
86
+ const request = condition.property === 'resourceQuery' ? query : fakeResourcePath;
87
+ if (condition && !condition.fn(request)) {
88
+ return false;
89
+ }
90
+ }
91
+ return true;
92
+ } });
93
+ delete res.test;
94
+ if (rawRule.rules) {
95
+ res.rules = rawRule.rules.map(rule => cloneRule(rule, refs, ruleCheck, ruleResource));
96
+ }
97
+ if (rawRule.oneOf) {
98
+ res.oneOf = rawRule.oneOf.map(rule => cloneRule(rule, refs, ruleCheck, ruleResource));
99
+ }
100
+ return res;
101
+ }
102
+ const langBlockRuleCheck = (query, rule) => query.type === 'custom' || !rule.conditions.length || query.lang != null;
103
+ const jsRuleCheck = (query) => query.type === 'template';
104
+ const jsRuleResource = (query, resource) => `${resource}.js`;
105
+ const langBlockRuleResource = (query, resource) => `${resource}.${query.lang}`;
106
+ class VueLoaderPlugin {
107
+ apply(compiler) {
108
+ // add NS marker so that the loader can detect and report missing plugin
109
+ compiler.hooks.compilation.tap(id, compilation => {
110
+ NormalModule.getCompilationHooks(compilation).loader.tap(id, (loaderContext) => {
111
+ loaderContext[NS] = true;
112
+ });
113
+ });
114
+ const rules = compiler.options.module.rules;
115
+ let rawVueRule;
116
+ let vueRules = [];
117
+ for (const rawRule of rules) {
118
+ // skip rules with 'enforce'. eg. rule for eslint-loader
119
+ if (rawRule.enforce) {
120
+ continue;
121
+ }
122
+ vueRules = match(rawRule, `foo.${(0, getMlSuffixName_1.default)()}`);
123
+ if (!vueRules.length) {
124
+ vueRules = match(rawRule, 'foo.vue.html');
125
+ }
126
+ if (vueRules.length > 0) {
127
+ if (rawRule.oneOf) {
128
+ throw new Error(`[VueLoaderPlugin Error] vue-loader currently does not support vue rules with oneOf.`);
129
+ }
130
+ rawVueRule = rawRule;
131
+ break;
132
+ }
133
+ }
134
+ if (!vueRules.length) {
135
+ throw new Error(`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +
136
+ `Make sure there is at least one root-level rule that matches .vue or .vue.html files.`);
137
+ }
138
+ // get the normlized "use" for vue files
139
+ const vueUse = vueRules.filter(rule => rule.type === 'use').map(rule => rule.value);
140
+ // get vue-loader options
141
+ const vueLoaderUseIndex = vueUse.findIndex(u =>
142
+ // FIXME: this code logic is incorrect when project paths starts with `vue-loader-something`
143
+ /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader));
144
+ if (vueLoaderUseIndex < 0) {
145
+ throw new Error(`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +
146
+ `Make sure the rule matching .vue files include vue-loader in its use.`);
147
+ }
148
+ // make sure vue-loader options has a known ident so that we can share
149
+ // options by reference in the template-loader by using a ref query like
150
+ // template-loader??vue-loader-options
151
+ const vueLoaderUse = vueUse[vueLoaderUseIndex];
152
+ const vueLoaderOptions = (vueLoaderUse.options = vueLoaderUse.options || {});
153
+ // for each user rule (expect the vue rule), create a cloned rule
154
+ // that targets the corresponding language blocks in *.vue files.
155
+ const refs = new Map();
156
+ const clonedRules = rules
157
+ .filter(r => r !== rawVueRule)
158
+ .map(rawRule => cloneRule(rawRule, refs, langBlockRuleCheck, langBlockRuleResource));
159
+ // fix conflict with config.loader and config.options when using config.use
160
+ delete rawVueRule.loader;
161
+ delete rawVueRule.options;
162
+ rawVueRule.use = vueUse;
163
+ // rule for template compiler
164
+ const templateCompilerRule = {
165
+ loader: require.resolve('vue-loader/dist/templateLoader'),
166
+ resourceQuery: (query) => {
167
+ if (!query) {
168
+ return false;
169
+ }
170
+ const parsed = querystring_1.default.parse(query.slice(1));
171
+ return parsed.vue != null && parsed.type === 'template';
172
+ },
173
+ options: vueLoaderOptions,
174
+ };
175
+ // for each rule that matches plain .js files, also create a clone and
176
+ // match it against the compiled template code inside *.vue files, so that
177
+ // compiled vue render functions receive the same treatment as user code
178
+ // (mostly babel)
179
+ const jsRulesForRenderFn = rules
180
+ .filter(r => r !== rawVueRule && match(r, 'test.js').length > 0)
181
+ .map(rawRule => cloneRule(rawRule, refs, jsRuleCheck, jsRuleResource));
182
+ // global pitcher (responsible for injecting template compiler loader & CSS
183
+ // post loader)
184
+ const pitcher = {
185
+ loader: require.resolve('vue-loader/dist/pitcher'),
186
+ resourceQuery: (query) => {
187
+ if (!query) {
188
+ return false;
189
+ }
190
+ const parsed = querystring_1.default.parse(query.slice(1));
191
+ return parsed.vue != null;
192
+ },
193
+ };
194
+ // replace original rules
195
+ compiler.options.module.rules = [
196
+ pitcher,
197
+ ...jsRulesForRenderFn,
198
+ templateCompilerRule,
199
+ ...clonedRules,
200
+ ...rules,
201
+ ];
202
+ }
203
+ }
204
+ VueLoaderPlugin.NS = NS;
205
+ exports.default = VueLoaderPlugin;
@@ -0,0 +1,8 @@
1
+ import { Compiler } from 'webpack';
2
+ /**
3
+ * 将 VueCompilerError 转换为 xhsml 错误提示
4
+ */
5
+ declare class XhsMpErrorTransformPlugin {
6
+ apply(compiler: Compiler): void;
7
+ }
8
+ export default XhsMpErrorTransformPlugin;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const getMlSuffixName_1 = __importDefault(require("../../utils/getMlSuffixName"));
7
+ /**
8
+ * 将 VueCompilerError 转换为 xhsml 错误提示
9
+ */
10
+ class XhsMpErrorTransformPlugin {
11
+ apply(compiler) {
12
+ compiler.hooks.afterCompile.tap('XhsMpErrorTransformPlugin', (compilation) => {
13
+ let vueCompilerErrors = [];
14
+ const errorFiles = new Set();
15
+ compilation.errors = compilation.errors.filter(err => {
16
+ if (/VueCompilerError/.test(err.message)) {
17
+ vueCompilerErrors.push(err);
18
+ return false;
19
+ }
20
+ return true;
21
+ });
22
+ // 同一个文件只取最后一个报错
23
+ vueCompilerErrors = vueCompilerErrors.reverse().reduce((acc, err) => {
24
+ if (err.module) {
25
+ const { context } = err.module;
26
+ if (!errorFiles.has(context)) {
27
+ err.stack = undefined;
28
+ err.message = err.message.replace(/VueCompilerError/g, `[ ${(0, getMlSuffixName_1.default)()} 文件编译错误 ]`).replace(/at createCompilerError .*?/g, '');
29
+ err.details = undefined;
30
+ acc.push(err);
31
+ errorFiles.add(context);
32
+ }
33
+ }
34
+ return acc;
35
+ }, []);
36
+ compilation.errors.push(...vueCompilerErrors);
37
+ });
38
+ }
39
+ }
40
+ exports.default = XhsMpErrorTransformPlugin;
@@ -0,0 +1,36 @@
1
+ import { Compiler } from 'webpack';
2
+ import { AppJSON } from '../../types/index';
3
+ interface IXhsMpJsonPluginOptions {
4
+ mpDir: string;
5
+ miniprogramDir: string;
6
+ extJsonPath?: string;
7
+ }
8
+ export interface IXhsData {
9
+ mpDir?: string;
10
+ miniprogramDir?: string;
11
+ appJSON?: AppJSON;
12
+ legacyAppJSON?: AppJSON;
13
+ jsonDependencies?: string[];
14
+ }
15
+ export type XhsCompiler = Compiler & {
16
+ xhsData: IXhsData;
17
+ };
18
+ /**
19
+ * 为 compiler 添加 xhsData 数据
20
+ */
21
+ declare class XhsMpJsonPlugin {
22
+ options: IXhsMpJsonPluginOptions;
23
+ appJSON: AppJSON;
24
+ legacyAppJSON: AppJSON;
25
+ shouldUpdateAppJson: 'first' | boolean;
26
+ jsonDependencies: Set<string>;
27
+ static getHooks: any;
28
+ constructor(options: IXhsMpJsonPluginOptions);
29
+ apply(compiler: XhsCompiler): void;
30
+ /**
31
+ * 1. 收集所有的 json 依赖
32
+ * 2. 为各个 loader 更新 appJson
33
+ */
34
+ updateAppJson(compiler: XhsCompiler): void;
35
+ }
36
+ export default XhsMpJsonPlugin;