-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathplugins.js
More file actions
80 lines (71 loc) · 2.79 KB
/
plugins.js
File metadata and controls
80 lines (71 loc) · 2.79 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import webpack from 'webpack'
import path, {resolve} from 'path'
import glob from 'glob'
import {makeRegExp} from './utils'
const projectDir = process.cwd()
const OVERRIDES_EXTENSIONS = '.+(js|jsx|ts|tsx)'
const getOverridePath = (relativePath) => {
// Perform lookups starting in the current projectDir
const generatedProjectOverride = glob.sync(
`${resolve(projectDir, ...relativePath)}${OVERRIDES_EXTENSIONS}`
)
return generatedProjectOverride?.length
? generatedProjectOverride?.[0]
: resolve(
'node_modules',
'@salesforce',
'pwa-kit-react-sdk',
'ssr',
'universal',
...relativePath.filter((item) => item !== 'src')
)
}
/**
* Allows users to override special SDK components by placing override
* files in certain magic locations in a project.
*
* @returns {webpack.NormalModuleReplacementPlugin}
*/
export const sdkReplacementPlugin = () => {
const overridables = [
{
path: makeRegExp('pwa-kit-react-sdk(/dist)?/ssr/universal/components/_app-config$'),
newPath: getOverridePath(['src', 'components', '_app-config', 'index'])
},
{
path: makeRegExp('pwa-kit-react-sdk(/dist)?/ssr/universal/components/_document$'),
newPath: getOverridePath(['src', 'components', '_document', 'index'])
},
{
path: makeRegExp('pwa-kit-react-sdk(/dist)?/ssr/universal/components/_app$'),
newPath: getOverridePath(['src', 'components', '_app', 'index'])
},
{
path: makeRegExp('pwa-kit-react-sdk(/dist)?/ssr/universal/components/_error$'),
newPath: getOverridePath(['src', 'components', '_error', 'index'])
},
{
path: makeRegExp('pwa-kit-react-sdk(/dist)?/ssr/universal/routes$'),
newPath: getOverridePath(['src', 'routes'])
}
]
const replacements = overridables?.filter?.((item) => item?.newPath)
return new webpack.NormalModuleReplacementPlugin(/.*/, (resource) => {
const resolved = path.resolve(resource.context, resource.request)
const replacement = replacements.find(({path}) => resolved.match(path))
const sdkPaths = [
path.join('packages', 'pwa-kit-react-sdk'),
path.join('node_modules', '@salesforce', 'pwa-kit-react-sdk')
]
const requestedFromSDK = sdkPaths.some((p) => resource.context.includes(p))
if (requestedFromSDK && replacement) {
resource.request = replacement.newPath
}
})
}