pluginWebpack5.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  5. }) : (function(o, m, k, k2) {
  6. if (k2 === undefined) k2 = k;
  7. o[k2] = m[k];
  8. }));
  9. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11. }) : function(o, v) {
  12. o["default"] = v;
  13. });
  14. var __importStar = (this && this.__importStar) || function (mod) {
  15. if (mod && mod.__esModule) return mod;
  16. var result = {};
  17. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  18. __setModuleDefault(result, mod);
  19. return result;
  20. };
  21. Object.defineProperty(exports, "__esModule", { value: true });
  22. const qs = __importStar(require("querystring"));
  23. const util_1 = require("./util");
  24. const resolveScript_1 = require("./resolveScript");
  25. const compiler_1 = require("./compiler");
  26. const descriptorCache_1 = require("./descriptorCache");
  27. const id = 'vue-loader-plugin';
  28. const NS = 'vue-loader';
  29. const NormalModule = require('webpack/lib/NormalModule');
  30. const BasicEffectRulePlugin = require('webpack/lib/rules/BasicEffectRulePlugin');
  31. const BasicMatcherRulePlugin = require('webpack/lib/rules/BasicMatcherRulePlugin');
  32. const UseEffectRulePlugin = require('webpack/lib/rules/UseEffectRulePlugin');
  33. const RuleSetCompiler = require('webpack/lib/rules/RuleSetCompiler');
  34. let objectMatcherRulePlugins = [];
  35. try {
  36. const ObjectMatcherRulePlugin = require('webpack/lib/rules/ObjectMatcherRulePlugin');
  37. objectMatcherRulePlugins.push(new ObjectMatcherRulePlugin('assert', 'assertions'), new ObjectMatcherRulePlugin('descriptionData'));
  38. }
  39. catch (e) {
  40. const DescriptionDataMatcherRulePlugin = require('webpack/lib/rules/DescriptionDataMatcherRulePlugin');
  41. objectMatcherRulePlugins.push(new DescriptionDataMatcherRulePlugin());
  42. }
  43. const ruleSetCompiler = new RuleSetCompiler([
  44. new BasicMatcherRulePlugin('test', 'resource'),
  45. new BasicMatcherRulePlugin('mimetype'),
  46. new BasicMatcherRulePlugin('dependency'),
  47. new BasicMatcherRulePlugin('include', 'resource'),
  48. new BasicMatcherRulePlugin('exclude', 'resource', true),
  49. new BasicMatcherRulePlugin('conditions'),
  50. new BasicMatcherRulePlugin('resource'),
  51. new BasicMatcherRulePlugin('resourceQuery'),
  52. new BasicMatcherRulePlugin('resourceFragment'),
  53. new BasicMatcherRulePlugin('realResource'),
  54. new BasicMatcherRulePlugin('issuer'),
  55. new BasicMatcherRulePlugin('compiler'),
  56. new BasicMatcherRulePlugin('issuerLayer'),
  57. ...objectMatcherRulePlugins,
  58. new BasicEffectRulePlugin('type'),
  59. new BasicEffectRulePlugin('sideEffects'),
  60. new BasicEffectRulePlugin('parser'),
  61. new BasicEffectRulePlugin('resolve'),
  62. new BasicEffectRulePlugin('generator'),
  63. new BasicEffectRulePlugin('layer'),
  64. new UseEffectRulePlugin(),
  65. ]);
  66. class VueLoaderPlugin {
  67. apply(compiler) {
  68. // @ts-ignore
  69. const normalModule = compiler.webpack.NormalModule || NormalModule;
  70. // add NS marker so that the loader can detect and report missing plugin
  71. compiler.hooks.compilation.tap(id, (compilation) => {
  72. normalModule
  73. .getCompilationHooks(compilation)
  74. .loader.tap(id, (loaderContext) => {
  75. loaderContext[NS] = true;
  76. });
  77. });
  78. const rules = compiler.options.module.rules;
  79. let rawVueRule;
  80. let vueRules = [];
  81. for (const rawRule of rules) {
  82. // skip rules with 'enforce'. eg. rule for eslint-loader
  83. if (rawRule.enforce) {
  84. continue;
  85. }
  86. vueRules = match(rawRule, 'foo.vue');
  87. if (!vueRules.length) {
  88. vueRules = match(rawRule, 'foo.vue.html');
  89. }
  90. if (vueRules.length > 0) {
  91. if (rawRule.oneOf) {
  92. throw new Error(`[VueLoaderPlugin Error] vue-loader currently does not support vue rules with oneOf.`);
  93. }
  94. rawVueRule = rawRule;
  95. break;
  96. }
  97. }
  98. if (!vueRules.length) {
  99. throw new Error(`[VueLoaderPlugin Error] No matching rule for .vue files found.\n` +
  100. `Make sure there is at least one root-level rule that matches .vue or .vue.html files.`);
  101. }
  102. // get the normalized "use" for vue files
  103. const vueUse = vueRules
  104. .filter((rule) => rule.type === 'use')
  105. .map((rule) => rule.value);
  106. // get vue-loader options
  107. const vueLoaderUseIndex = vueUse.findIndex((u) => {
  108. // FIXME: this code logic is incorrect when project paths starts with `vue-loader-something`
  109. return /^vue-loader|(\/|\\|@)vue-loader/.test(u.loader);
  110. });
  111. if (vueLoaderUseIndex < 0) {
  112. throw new Error(`[VueLoaderPlugin Error] No matching use for vue-loader is found.\n` +
  113. `Make sure the rule matching .vue files include vue-loader in its use.`);
  114. }
  115. // make sure vue-loader options has a known ident so that we can share
  116. // options by reference in the template-loader by using a ref query like
  117. // template-loader??vue-loader-options
  118. const vueLoaderUse = vueUse[vueLoaderUseIndex];
  119. const vueLoaderOptions = (vueLoaderUse.options =
  120. vueLoaderUse.options || {});
  121. const enableInlineMatchResource = vueLoaderOptions.experimentalInlineMatchResource;
  122. // for each user rule (except the vue rule), create a cloned rule
  123. // that targets the corresponding language blocks in *.vue files.
  124. const refs = new Map();
  125. const clonedRules = rules
  126. .filter((r) => r !== rawVueRule)
  127. .map((rawRule) => cloneRule(rawRule, refs, langBlockRuleCheck, langBlockRuleResource));
  128. // fix conflict with config.loader and config.options when using config.use
  129. delete rawVueRule.loader;
  130. delete rawVueRule.options;
  131. rawVueRule.use = vueUse;
  132. // rule for template compiler
  133. const templateCompilerRule = {
  134. loader: require.resolve('./templateLoader'),
  135. resourceQuery: (query) => {
  136. if (!query) {
  137. return false;
  138. }
  139. const parsed = qs.parse(query.slice(1));
  140. return parsed.vue != null && parsed.type === 'template';
  141. },
  142. options: vueLoaderOptions,
  143. };
  144. // for each rule that matches plain .js files, also create a clone and
  145. // match it against the compiled template code inside *.vue files, so that
  146. // compiled vue render functions receive the same treatment as user code
  147. // (mostly babel)
  148. const jsRulesForRenderFn = rules
  149. .filter((r) => r !== rawVueRule &&
  150. (match(r, 'test.js').length > 0 || match(r, 'test.ts').length > 0))
  151. .map((rawRule) => cloneRule(rawRule, refs, jsRuleCheck, jsRuleResource));
  152. // global pitcher (responsible for injecting template compiler loader & CSS
  153. // post loader)
  154. const pitcher = {
  155. loader: require.resolve('./pitcher'),
  156. resourceQuery: (query) => {
  157. if (!query) {
  158. return false;
  159. }
  160. const parsed = qs.parse(query.slice(1));
  161. return parsed.vue != null;
  162. },
  163. options: vueLoaderOptions,
  164. };
  165. // replace original rules
  166. if (enableInlineMatchResource) {
  167. // Match rules using `vue-loader`
  168. const vueLoaderRules = rules.filter((rule) => {
  169. const matchOnce = (use) => {
  170. let loaderString = '';
  171. if (!use) {
  172. return loaderString;
  173. }
  174. if (typeof use === 'string') {
  175. loaderString = use;
  176. }
  177. else if (Array.isArray(use)) {
  178. loaderString = matchOnce(use[0]);
  179. }
  180. else if (typeof use === 'object' && use.loader) {
  181. loaderString = use.loader;
  182. }
  183. return loaderString;
  184. };
  185. const loader = rule.loader || matchOnce(rule.use);
  186. return (loader === require('../package.json').name ||
  187. loader.startsWith(require.resolve('./index')));
  188. });
  189. compiler.options.module.rules = [
  190. pitcher,
  191. ...rules.filter((rule) => !vueLoaderRules.includes(rule)),
  192. templateCompilerRule,
  193. ...clonedRules,
  194. ...vueLoaderRules,
  195. ];
  196. }
  197. else {
  198. compiler.options.module.rules = [
  199. pitcher,
  200. ...jsRulesForRenderFn,
  201. templateCompilerRule,
  202. ...clonedRules,
  203. ...rules,
  204. ];
  205. }
  206. // 3.3 HMR support for imported types
  207. if ((0, util_1.needHMR)(vueLoaderOptions, compiler.options) &&
  208. compiler_1.compiler.invalidateTypeCache) {
  209. compiler.hooks.afterCompile.tap(id, (compilation) => {
  210. if (compilation.compiler === compiler) {
  211. for (const file of resolveScript_1.typeDepToSFCMap.keys()) {
  212. compilation.fileDependencies.add(file);
  213. }
  214. }
  215. });
  216. compiler.hooks.watchRun.tap(id, () => {
  217. if (!compiler.modifiedFiles)
  218. return;
  219. for (const file of compiler.modifiedFiles) {
  220. compiler_1.compiler.invalidateTypeCache(file);
  221. const affectedSFCs = resolveScript_1.typeDepToSFCMap.get(file);
  222. if (affectedSFCs) {
  223. for (const sfc of affectedSFCs) {
  224. // bust script resolve cache
  225. const desc = descriptorCache_1.descriptorCache.get(sfc);
  226. if (desc)
  227. resolveScript_1.clientCache.delete(desc);
  228. // force update importing SFC
  229. // @ts-ignore
  230. compiler.fileTimestamps.set(sfc, {
  231. safeTime: Date.now(),
  232. timestamp: Date.now(),
  233. });
  234. }
  235. }
  236. }
  237. for (const file of compiler.removedFiles) {
  238. compiler_1.compiler.invalidateTypeCache(file);
  239. }
  240. });
  241. }
  242. }
  243. }
  244. VueLoaderPlugin.NS = NS;
  245. const matcherCache = new WeakMap();
  246. function match(rule, fakeFile) {
  247. let ruleSet = matcherCache.get(rule);
  248. if (!ruleSet) {
  249. // skip the `include` check when locating the vue rule
  250. const clonedRawRule = Object.assign({}, rule);
  251. delete clonedRawRule.include;
  252. ruleSet = ruleSetCompiler.compile([clonedRawRule]);
  253. matcherCache.set(rule, ruleSet);
  254. }
  255. return ruleSet.exec({
  256. resource: fakeFile,
  257. });
  258. }
  259. const langBlockRuleCheck = (query, rule) => {
  260. return (query.type === 'custom' || !rule.conditions.length || query.lang != null);
  261. };
  262. const langBlockRuleResource = (query, resource) => `${resource}.${query.lang}`;
  263. const jsRuleCheck = (query) => {
  264. return query.type === 'template';
  265. };
  266. const jsRuleResource = (query, resource) => `${resource}.${query.ts ? `ts` : `js`}`;
  267. let uid = 0;
  268. function cloneRule(rawRule, refs, ruleCheck, ruleResource) {
  269. const compiledRule = ruleSetCompiler.compileRule(`clonedRuleSet-${++uid}`, rawRule, refs);
  270. // do not process rule with enforce
  271. if (!rawRule.enforce) {
  272. const ruleUse = compiledRule.effects
  273. .filter((effect) => effect.type === 'use')
  274. .map((effect) => effect.value);
  275. // fix conflict with config.loader and config.options when using config.use
  276. delete rawRule.loader;
  277. delete rawRule.options;
  278. rawRule.use = ruleUse;
  279. }
  280. let currentResource;
  281. const res = Object.assign(Object.assign({}, rawRule), { resource: (resources) => {
  282. currentResource = resources;
  283. return true;
  284. }, resourceQuery: (query) => {
  285. if (!query) {
  286. return false;
  287. }
  288. const parsed = qs.parse(query.slice(1));
  289. if (parsed.vue == null) {
  290. return false;
  291. }
  292. if (!ruleCheck(parsed, compiledRule)) {
  293. return false;
  294. }
  295. const fakeResourcePath = ruleResource(parsed, currentResource);
  296. for (const condition of compiledRule.conditions) {
  297. // add support for resourceQuery
  298. const request = condition.property === 'resourceQuery' ? query : fakeResourcePath;
  299. if (condition && !condition.fn(request)) {
  300. return false;
  301. }
  302. }
  303. return true;
  304. } });
  305. delete res.test;
  306. if (rawRule.rules) {
  307. res.rules = rawRule.rules.map((rule) => cloneRule(rule, refs, ruleCheck, ruleResource));
  308. }
  309. if (rawRule.oneOf) {
  310. res.oneOf = rawRule.oneOf.map((rule) => cloneRule(rule, refs, ruleCheck, ruleResource));
  311. }
  312. return res;
  313. }
  314. exports.default = VueLoaderPlugin;