|
| 1 | +import * as fs from 'fs'; |
| 2 | +import * as path from 'path'; |
| 3 | +import * as glob from 'glob'; |
| 4 | +import * as denodeify from 'denodeify'; |
| 5 | + |
| 6 | +const globPromise = <any>denodeify(glob); |
| 7 | +const statPromise = <any>denodeify(fs.stat); |
| 8 | + |
| 9 | +export interface GlobCopyWebpackPluginOptions { |
| 10 | + patterns: string[]; |
| 11 | + globOptions: any; |
| 12 | +} |
| 13 | + |
| 14 | +export class GlobCopyWebpackPlugin { |
| 15 | + constructor(private options: GlobCopyWebpackPluginOptions) { } |
| 16 | + |
| 17 | + apply(compiler: any): void { |
| 18 | + let { patterns, globOptions } = this.options; |
| 19 | + let context = globOptions.cwd || compiler.options.context; |
| 20 | + |
| 21 | + // convert dir patterns to globs |
| 22 | + patterns = patterns.map(pattern => fs.statSync(path.resolve(context, pattern)).isDirectory() |
| 23 | + ? pattern += '/**/*' |
| 24 | + : pattern |
| 25 | + ); |
| 26 | + |
| 27 | + // force nodir option, since we can't add dirs to assets |
| 28 | + globOptions.nodir = true; |
| 29 | + |
| 30 | + compiler.plugin('emit', (compilation: any, cb: any) => { |
| 31 | + let globs = patterns.map(pattern => globPromise(pattern, globOptions)); |
| 32 | + |
| 33 | + let addAsset = (relPath: string) => compilation.assets[relPath] |
| 34 | + // don't re-add to assets |
| 35 | + ? Promise.resolve() |
| 36 | + : statPromise(path.resolve(context, relPath)) |
| 37 | + .then((stat: any) => compilation.assets[relPath] = { |
| 38 | + size: () => stat.size, |
| 39 | + source: () => fs.readFileSync(path.resolve(context, relPath)) |
| 40 | + }); |
| 41 | + |
| 42 | + Promise.all(globs) |
| 43 | + // flatten results |
| 44 | + .then(globResults => [].concat.apply([], globResults)) |
| 45 | + // add each file to compilation assets |
| 46 | + .then(relPaths => relPaths.forEach((relPath: string) => addAsset(relPath))) |
| 47 | + .catch((err) => compilation.errors.push(err)) |
| 48 | + .then(cb); |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
0 commit comments