UNPKG

2.34 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const webpack_1 = require("webpack");
4const path = require("path");
5function interpolateName(loaderResourcePath, loaderResourceQuery, name, options) {
6 const filename = name || '[hash].[ext]';
7 const context = options.context;
8 const content = options.content;
9 let ext = 'bin';
10 let basename = 'file';
11 let directory = '';
12 let folder = '';
13 let query = '';
14 if (loaderResourcePath) {
15 const parsed = path.parse(loaderResourcePath);
16 let resourcePath = loaderResourcePath;
17 if (parsed.ext) {
18 ext = parsed.ext.substr(1);
19 }
20 if (parsed.dir) {
21 basename = parsed.name;
22 resourcePath = parsed.dir + path.sep;
23 }
24 if (typeof context !== 'undefined') {
25 directory = path
26 .relative(context, resourcePath + '_')
27 .replace(/\\/g, '/')
28 .replace(/\.\.(\/)?/g, '_$1');
29 directory = directory.substr(0, directory.length - 1);
30 }
31 else {
32 directory = resourcePath.replace(/\\/g, '/').replace(/\.\.(\/)?/g, '_$1');
33 }
34 if (directory.length === 1) {
35 directory = '';
36 }
37 else if (directory.length > 1) {
38 folder = path.basename(directory);
39 }
40 }
41 if (loaderResourceQuery && loaderResourceQuery.length > 1) {
42 query = loaderResourceQuery;
43 const hashIdx = query.indexOf('#');
44 if (hashIdx >= 0) {
45 query = query.substr(0, hashIdx);
46 }
47 }
48 let url = filename;
49 if (content) {
50 const hash = webpack_1.util.createHash('md4');
51 hash.update(content);
52 // Match hash template
53 url = url
54 // `hash` and `contenthash` are same in `loader-utils` context
55 // let's keep `hash` for backward compatibility
56 .replace(/\[(?:([^:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi, `${hash.digest('hex')}`);
57 }
58 url = url
59 .replace(/\[ext\]/gi, () => ext)
60 .replace(/\[name\]/gi, () => basename)
61 .replace(/\[path\]/gi, () => directory)
62 .replace(/\[folder\]/gi, () => folder)
63 .replace(/\[query\]/gi, () => query);
64 return url;
65}
66exports.default = interpolateName;