-
Notifications
You must be signed in to change notification settings - Fork 370
/
AddModePlugin.js
44 lines (42 loc) · 1.67 KB
/
AddModePlugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const path = require('path')
const stringifyQuery = require('../utils/stringify-query')
const parseQuery = require('loader-utils').parseQuery
const { matchCondition } = require('../utils/match-condition')
const addInfix = require('../utils/add-infix')
const { JSON_JS_EXT } = require('../utils/const')
module.exports = class AddModePlugin {
constructor (source, mode, fileConditionRules, target) {
this.source = source
this.target = target
this.mode = mode
this.fileConditionRules = fileConditionRules
}
apply (resolver) {
const target = resolver.ensureHook(this.target)
const mode = this.mode
resolver.getHook(this.source).tapAsync('AddModePlugin', (request, resolveContext, callback) => {
if (request.mode || request.env) {
return callback()
}
const obj = {
mode
}
const resourcePath = request.path
let extname = ''
if (resourcePath.endsWith(JSON_JS_EXT)) {
extname = JSON_JS_EXT
} else {
extname = path.extname(resourcePath)
}
// 当前资源没有后缀名或者路径不符合fileConditionRules规则时,直接返回
if (!extname || !matchCondition(resourcePath, this.fileConditionRules)) return callback()
const queryObj = parseQuery(request.query || '?')
queryObj.mode = mode
queryObj.infix = `${queryObj.infix || ''}.${mode}`
obj.query = stringifyQuery(queryObj)
obj.path = addInfix(resourcePath, mode, extname)
obj.relativePath = request.relativePath && addInfix(request.relativePath, mode, extname)
resolver.doResolve(target, Object.assign({}, request, obj), 'add mode: ' + mode, resolveContext, callback)
})
}
}