forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
copy-file-plugin.ts
68 lines (62 loc) · 1.62 KB
/
copy-file-plugin.ts
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
import { promises as fs } from 'fs'
import loaderUtils from 'next/dist/compiled/loader-utils'
import {
isWebpack5,
sources,
webpack,
} from 'next/dist/compiled/webpack/webpack'
const PLUGIN_NAME = 'CopyFilePlugin'
export class CopyFilePlugin {
private source: string
private name: string
private minimize: boolean
private info?: object
constructor({
source,
name,
minimize,
info,
}: {
source: string
name: string
minimize: boolean
info?: object
}) {
this.source = source
this.name = name
this.minimize = minimize
this.info = info
}
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const hook = isWebpack5
? // @ts-ignore
compilation.hooks.processAssets
: compilation.hooks.additionalAssets
hook.tapPromise(
isWebpack5
? {
name: PLUGIN_NAME,
stage: this.minimize
? // @ts-ignore
webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
: // @ts-ignore
webpack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
}
: PLUGIN_NAME,
async () => {
const content = await fs.readFile(this.source, 'utf8')
const file = loaderUtils.interpolateName(
{ resourcePath: this.source },
this.name,
{ content, context: compiler.context }
)
// @ts-ignore
compilation.emitAsset(file, new sources.RawSource(content), {
...this.info,
})
}
)
})
}
}