index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. var __importDefault = (this && this.__importDefault) || function (mod) {
  22. return (mod && mod.__esModule) ? mod : { "default": mod };
  23. };
  24. Object.defineProperty(exports, "__esModule", { value: true });
  25. exports.VueLoaderPlugin = void 0;
  26. const path = __importStar(require("path"));
  27. const qs = __importStar(require("querystring"));
  28. const hash = require("hash-sum");
  29. const compiler_1 = require("./compiler");
  30. const select_1 = require("./select");
  31. const hotReload_1 = require("./hotReload");
  32. const cssModules_1 = require("./cssModules");
  33. const formatError_1 = require("./formatError");
  34. const plugin_1 = __importDefault(require("./plugin"));
  35. exports.VueLoaderPlugin = plugin_1.default;
  36. const resolveScript_1 = require("./resolveScript");
  37. const descriptorCache_1 = require("./descriptorCache");
  38. const util_1 = require("./util");
  39. let errorEmitted = false;
  40. const { parse } = compiler_1.compiler;
  41. const exportHelperPath = require.resolve('./exportHelper');
  42. function loader(source) {
  43. var _a;
  44. const loaderContext = this;
  45. // check if plugin is installed
  46. if (!errorEmitted &&
  47. !loaderContext['thread-loader'] &&
  48. !loaderContext[plugin_1.default.NS]) {
  49. loaderContext.emitError(new Error(`vue-loader was used without the corresponding plugin. ` +
  50. `Make sure to include VueLoaderPlugin in your webpack config.`));
  51. errorEmitted = true;
  52. }
  53. const stringifyRequest = (r) => (0, util_1.stringifyRequest)(loaderContext, r);
  54. const { mode, target, sourceMap, rootContext, resourcePath, resourceQuery: _resourceQuery = '', _compiler, } = loaderContext;
  55. const isWebpack5 = (0, util_1.testWebpack5)(_compiler);
  56. const rawQuery = _resourceQuery.slice(1);
  57. const incomingQuery = qs.parse(rawQuery);
  58. const resourceQuery = rawQuery ? `&${rawQuery}` : '';
  59. const options = ((0, util_1.getOptions)(loaderContext) || {});
  60. const enableInlineMatchResource = isWebpack5 && Boolean(options.experimentalInlineMatchResource);
  61. const isServer = (_a = options.isServerBuild) !== null && _a !== void 0 ? _a : target === 'node';
  62. const isProduction = mode === 'production' || process.env.NODE_ENV === 'production';
  63. const filename = resourcePath.replace(/\?.*$/, '');
  64. const { descriptor, errors } = parse(source, {
  65. filename,
  66. sourceMap,
  67. templateParseOptions: options.compilerOptions,
  68. });
  69. const asCustomElement = typeof options.customElement === 'boolean'
  70. ? options.customElement
  71. : (options.customElement || /\.ce\.vue$/).test(filename);
  72. // cache descriptor
  73. (0, descriptorCache_1.setDescriptor)(filename, descriptor);
  74. if (errors.length) {
  75. errors.forEach((err) => {
  76. (0, formatError_1.formatError)(err, source, resourcePath);
  77. loaderContext.emitError(err);
  78. });
  79. return ``;
  80. }
  81. // module id for scoped CSS & hot-reload
  82. const rawShortFilePath = path
  83. .relative(rootContext || process.cwd(), filename)
  84. .replace(/^(\.\.[\/\\])+/, '');
  85. const shortFilePath = rawShortFilePath.replace(/\\/g, '/');
  86. const id = hash(isProduction
  87. ? shortFilePath + '\n' + source.replace(/\r\n/g, '\n')
  88. : shortFilePath);
  89. // if the query has a type field, this is a language block request
  90. // e.g. foo.vue?type=template&id=xxxxx
  91. // and we will return early
  92. if (incomingQuery.type) {
  93. return (0, select_1.selectBlock)(descriptor, id, options, loaderContext, incomingQuery, !!options.appendExtension);
  94. }
  95. // feature information
  96. const hasScoped = descriptor.styles.some((s) => s.scoped);
  97. const needsHotReload = !isServer &&
  98. !isProduction &&
  99. !!(descriptor.script || descriptor.scriptSetup || descriptor.template) &&
  100. options.hotReload !== false;
  101. // extra properties to attach to the script object
  102. // we need to do this in a tree-shaking friendly manner
  103. const propsToAttach = [];
  104. // script
  105. let scriptImport = `const script = {}`;
  106. let isTS = false;
  107. const { script, scriptSetup } = descriptor;
  108. if (script || scriptSetup) {
  109. const lang = (script === null || script === void 0 ? void 0 : script.lang) || (scriptSetup === null || scriptSetup === void 0 ? void 0 : scriptSetup.lang);
  110. isTS = !!(lang && /tsx?/.test(lang));
  111. const externalQuery = Boolean(script && !scriptSetup && script.src)
  112. ? `&external`
  113. : ``;
  114. const src = (script && !scriptSetup && script.src) || resourcePath;
  115. const attrsQuery = attrsToQuery((scriptSetup || script).attrs, 'js');
  116. const query = `?vue&type=script${attrsQuery}${resourceQuery}${externalQuery}`;
  117. let scriptRequest;
  118. if (enableInlineMatchResource) {
  119. scriptRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, lang || 'js'));
  120. }
  121. else {
  122. scriptRequest = stringifyRequest(src + query);
  123. }
  124. scriptImport =
  125. `import script from ${scriptRequest}\n` +
  126. // support named exports
  127. `export * from ${scriptRequest}`;
  128. }
  129. // template
  130. let templateImport = ``;
  131. let templateRequest;
  132. const renderFnName = isServer ? `ssrRender` : `render`;
  133. const useInlineTemplate = (0, resolveScript_1.canInlineTemplate)(descriptor, isProduction);
  134. if (descriptor.template && !useInlineTemplate) {
  135. const src = descriptor.template.src || resourcePath;
  136. const externalQuery = Boolean(descriptor.template.src) ? `&external` : ``;
  137. const idQuery = `&id=${id}`;
  138. const scopedQuery = hasScoped ? `&scoped=true` : ``;
  139. const attrsQuery = attrsToQuery(descriptor.template.attrs);
  140. const tsQuery = options.enableTsInTemplate !== false && isTS ? `&ts=true` : ``;
  141. const query = `?vue&type=template${idQuery}${scopedQuery}${tsQuery}${attrsQuery}${resourceQuery}${externalQuery}`;
  142. if (enableInlineMatchResource) {
  143. templateRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, options.enableTsInTemplate !== false && isTS ? 'ts' : 'js'));
  144. }
  145. else {
  146. templateRequest = stringifyRequest(src + query);
  147. }
  148. templateImport = `import { ${renderFnName} } from ${templateRequest}`;
  149. propsToAttach.push([renderFnName, renderFnName]);
  150. }
  151. // styles
  152. let stylesCode = ``;
  153. let hasCSSModules = false;
  154. const nonWhitespaceRE = /\S+/;
  155. if (descriptor.styles.length) {
  156. descriptor.styles
  157. .filter((style) => style.src || nonWhitespaceRE.test(style.content))
  158. .forEach((style, i) => {
  159. const src = style.src || resourcePath;
  160. const attrsQuery = attrsToQuery(style.attrs, 'css');
  161. const lang = String(style.attrs.lang || 'css');
  162. // make sure to only pass id when necessary so that we don't inject
  163. // duplicate tags when multiple components import the same css file
  164. const idQuery = !style.src || style.scoped ? `&id=${id}` : ``;
  165. const inlineQuery = asCustomElement ? `&inline` : ``;
  166. const externalQuery = Boolean(style.src) ? `&external` : ``;
  167. const query = `?vue&type=style&index=${i}${idQuery}${inlineQuery}${attrsQuery}${resourceQuery}${externalQuery}`;
  168. let styleRequest;
  169. if (enableInlineMatchResource) {
  170. styleRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, lang));
  171. }
  172. else {
  173. styleRequest = stringifyRequest(src + query);
  174. }
  175. if (style.module) {
  176. if (asCustomElement) {
  177. loaderContext.emitError(new Error(`<style module> is not supported in custom element mode.`));
  178. }
  179. if (!hasCSSModules) {
  180. stylesCode += `\nconst cssModules = {}`;
  181. propsToAttach.push([`__cssModules`, `cssModules`]);
  182. hasCSSModules = true;
  183. }
  184. stylesCode += (0, cssModules_1.genCSSModulesCode)(id, i, styleRequest, style.module, needsHotReload);
  185. }
  186. else {
  187. if (asCustomElement) {
  188. stylesCode += `\nimport _style_${i} from ${styleRequest}`;
  189. }
  190. else {
  191. stylesCode += `\nimport ${styleRequest}`;
  192. }
  193. }
  194. // TODO SSR critical CSS collection
  195. });
  196. if (asCustomElement) {
  197. propsToAttach.push([
  198. `styles`,
  199. `[${descriptor.styles.map((_, i) => `_style_${i}`)}]`,
  200. ]);
  201. }
  202. }
  203. let code = [templateImport, scriptImport, stylesCode]
  204. .filter(Boolean)
  205. .join('\n');
  206. // attach scope Id for runtime use
  207. if (hasScoped) {
  208. propsToAttach.push([`__scopeId`, `"data-v-${id}"`]);
  209. }
  210. // Expose filename. This is used by the devtools and Vue runtime warnings.
  211. if (!isProduction) {
  212. // Expose the file's full path in development, so that it can be opened
  213. // from the devtools.
  214. propsToAttach.push([
  215. `__file`,
  216. JSON.stringify(rawShortFilePath.replace(/\\/g, '/')),
  217. ]);
  218. }
  219. else if (options.exposeFilename) {
  220. // Libraries can opt-in to expose their components' filenames in production builds.
  221. // For security reasons, only expose the file's basename in production.
  222. propsToAttach.push([`__file`, JSON.stringify(path.basename(resourcePath))]);
  223. }
  224. // custom blocks
  225. if (descriptor.customBlocks && descriptor.customBlocks.length) {
  226. code += `\n/* custom blocks */\n`;
  227. code +=
  228. descriptor.customBlocks
  229. .map((block, i) => {
  230. const src = block.attrs.src || resourcePath;
  231. const attrsQuery = attrsToQuery(block.attrs);
  232. const blockTypeQuery = `&blockType=${qs.escape(block.type)}`;
  233. const issuerQuery = block.attrs.src
  234. ? `&issuerPath=${qs.escape(resourcePath)}`
  235. : '';
  236. const externalQuery = Boolean(block.attrs.src) ? `&external` : ``;
  237. const query = `?vue&type=custom&index=${i}${blockTypeQuery}${issuerQuery}${attrsQuery}${resourceQuery}${externalQuery}`;
  238. let customRequest;
  239. if (enableInlineMatchResource) {
  240. customRequest = stringifyRequest((0, util_1.genMatchResource)(this, src, query, block.attrs.lang));
  241. }
  242. else {
  243. customRequest = stringifyRequest(src + query);
  244. }
  245. return (`import block${i} from ${customRequest}\n` +
  246. `if (typeof block${i} === 'function') block${i}(script)`);
  247. })
  248. .join(`\n`) + `\n`;
  249. }
  250. // finalize
  251. if (!propsToAttach.length) {
  252. code += `\n\nconst __exports__ = script;`;
  253. }
  254. else {
  255. code += `\n\nimport exportComponent from ${stringifyRequest(exportHelperPath)}`;
  256. code += `\nconst __exports__ = /*#__PURE__*/exportComponent(script, [${propsToAttach
  257. .map(([key, val]) => `['${key}',${val}]`)
  258. .join(',')}])`;
  259. }
  260. if (needsHotReload) {
  261. code += (0, hotReload_1.genHotReloadCode)(id, templateRequest);
  262. }
  263. code += `\n\nexport default __exports__`;
  264. return code;
  265. }
  266. exports.default = loader;
  267. // these are built-in query parameters so should be ignored
  268. // if the user happen to add them as attrs
  269. const ignoreList = ['id', 'index', 'src', 'type'];
  270. function attrsToQuery(attrs, langFallback) {
  271. let query = ``;
  272. for (const name in attrs) {
  273. const value = attrs[name];
  274. if (!ignoreList.includes(name)) {
  275. query += `&${qs.escape(name)}=${value ? qs.escape(String(value)) : ``}`;
  276. }
  277. }
  278. if (langFallback && !(`lang` in attrs)) {
  279. query += `&lang=${langFallback}`;
  280. }
  281. return query;
  282. }