|
1 | | -const { join } = require('path'); |
2 | 1 | const { RawSource } = require('webpack-sources'); |
| 2 | +const npmCheck = require('npm-check'); |
| 3 | + |
3 | 4 |
|
4 | 5 | class MicroservicesWebpackPlugin { |
5 | 6 | constructor(config = {}) { |
6 | 7 | this.modules = config.modules || []; |
7 | 8 | this.url = config.url || 'https://unpkg.com/:name@:version/:path'; |
8 | 9 | this.paramsRegex = /:([a-z]+)/gi; |
9 | | - this.node_modules = join(process.cwd(), 'node_modules'); |
10 | | - |
11 | | - this.modules = this.modules |
12 | | - .map(({ name, ...other }) => ({ |
13 | | - name, |
14 | | - ...other, |
15 | | - version: require(join(this.node_modules, name, 'package.json')).version |
16 | | - })) |
17 | | - .map(({ name, version, path }) => { |
18 | | - if (!path.includes('.js')) { |
19 | | - throw new Error(`Unsupported extension in ${path}`); |
20 | | - } |
| 10 | + } |
21 | 11 |
|
22 | | - const cdn = this.url.replace(this.paramsRegex, (_, type) => ({ |
23 | | - name, |
24 | | - version, |
25 | | - path |
26 | | - })[type]); |
| 12 | + async createUrlsToModules(modules) { |
| 13 | + const currentState = await npmCheck(); |
27 | 14 |
|
28 | | - return { |
29 | | - name, |
30 | | - cdn |
31 | | - } |
32 | | - }) |
33 | | - } |
| 15 | + const packages = currentState |
| 16 | + .get('packages') |
| 17 | + .reduce((list, { moduleName, ...others }) => list.set(moduleName, others), new Map()); |
| 18 | + |
| 19 | + return modules |
| 20 | + .map(({ name, ...other }) => ({ |
| 21 | + name, |
| 22 | + ...other, |
| 23 | + version: packages.get(name).installed |
| 24 | + })) |
| 25 | + .map(({ name, version, path }) => { |
| 26 | + if (!path.includes('.js')) { |
| 27 | + throw new Error(`Unsupported extension in ${path}`); |
| 28 | + } |
| 29 | + |
| 30 | + const cdn = this.url.replace(this.paramsRegex, (_, type) => ({ |
| 31 | + name, |
| 32 | + version, |
| 33 | + path |
| 34 | + })[type]); |
| 35 | + |
| 36 | + return { |
| 37 | + name, |
| 38 | + cdn |
| 39 | + } |
| 40 | + }); |
| 41 | + } |
34 | 42 |
|
35 | 43 | apply(compiler) { |
36 | 44 | compiler.hooks.emit.tapAsync(MicroservicesWebpackPlugin.name, this.tapAsync.bind(this)) |
37 | 45 | compiler.options.externals = this.modules.map(({ name }) => name) |
38 | 46 | } |
39 | 47 |
|
40 | | - tapAsync(compilation, callback) { |
| 48 | + async tapAsync(compilation, callback) { |
| 49 | + this.modules = await this.createUrlsToModules(this.modules); |
| 50 | + |
41 | 51 | compilation.assets = Object.keys(compilation.assets) |
42 | 52 | .map((fileName) => { |
43 | 53 | if (!fileName.includes('.js')) { |
|
0 commit comments