File size: 8,333 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/**
COPYRIGHT (c) 2017-present James Kyle <me@thejameskyle.com>
 MIT License
 Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
 The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
*/
// Implementation of this PR: https://github.com/jamiebuilds/react-loadable/pull/132
// Modified to strip out unneeded results for Next's specific use case

import type {
  DynamicCssManifest,
  ReactLoadableManifest,
} from '../../../server/load-components'
import path from 'path'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { DYNAMIC_CSS_MANIFEST } from '../../../shared/lib/constants'

function getModuleId(compilation: any, module: any): string | number {
  return compilation.chunkGraph.getModuleId(module)
}

function getModuleFromDependency(
  compilation: any,
  dep: any
): webpack.Module & { resource?: string } {
  return compilation.moduleGraph.getModule(dep)
}

function getOriginModuleFromDependency(
  compilation: any,
  dep: any
): webpack.Module & { resource?: string } {
  return compilation.moduleGraph.getParentModule(dep)
}

function getChunkGroupFromBlock(
  compilation: any,
  block: any
): webpack.Compilation['chunkGroups'] {
  return compilation.chunkGraph.getBlockChunkGroup(block)
}

function buildManifest(
  _compiler: webpack.Compiler,
  compilation: webpack.Compilation,
  projectSrcDir: string | undefined,
  dev: boolean,
  shouldCreateDynamicCssManifest: boolean
): {
  reactLoadableManifest: ReactLoadableManifest
  dynamicCssManifest: DynamicCssManifest
} {
  if (!projectSrcDir) {
    return {
      reactLoadableManifest: {},
      dynamicCssManifest: [],
    }
  }
  const dynamicCssManifestSet = new Set<string>()
  let manifest: ReactLoadableManifest = {}

  // This is allowed:
  // import("./module"); <- ImportDependency

  // We don't support that:
  // import(/* webpackMode: "eager" */ "./module") <- ImportEagerDependency
  // import(`./module/${param}`) <- ImportContextDependency

  // Find all dependencies blocks which contains a `import()` dependency
  const handleBlock = (block: any) => {
    block.blocks.forEach(handleBlock)
    const chunkGroup = getChunkGroupFromBlock(compilation, block)
    for (const dependency of block.dependencies) {
      if (dependency.type.startsWith('import()')) {
        // get the referenced module
        const module = getModuleFromDependency(compilation, dependency)
        if (!module) return

        // get the module containing the import()
        const originModule = getOriginModuleFromDependency(
          compilation,
          dependency
        )
        const originRequest: string | undefined = originModule?.resource
        if (!originRequest) return

        // We construct a "unique" key from origin module and request
        // It's not perfect unique, but that will be fine for us.
        // We also need to construct the same in the babel plugin.
        const key = `${path.relative(projectSrcDir, originRequest)} -> ${
          dependency.request
        }`

        // Capture all files that need to be loaded.
        const files = new Set<string>()

        if (manifest[key]) {
          // In the "rare" case where multiple chunk groups
          // are created for the same `import()` or multiple
          // import()s reference the same module, we merge
          // the files to make sure to not miss files
          // This may cause overfetching in edge cases.
          for (const file of manifest[key].files) {
            files.add(file)
          }
        }

        // There might not be a chunk group when all modules
        // are already loaded. In this case we only need need
        // the module id and no files
        if (chunkGroup) {
          for (const chunk of (chunkGroup as any)
            .chunks as webpack.Compilation['chunks']) {
            chunk.files.forEach((file: string) => {
              if (
                (file.endsWith('.js') || file.endsWith('.css')) &&
                file.match(/^static\/(chunks|css)\//)
              ) {
                files.add(file)

                if (shouldCreateDynamicCssManifest && file.endsWith('.css')) {
                  dynamicCssManifestSet.add(file)
                }
              }
            })
          }
        }

        // usually we have to add the parent chunk groups too
        // but we assume that all parents are also imported by
        // next/dynamic so they are loaded by the same technique

        // add the id and files to the manifest
        const id = dev ? key : getModuleId(compilation, module)
        manifest[key] = { id, files: Array.from(files) }
      }
    }
  }
  for (const module of compilation.modules) {
    module.blocks.forEach(handleBlock)
  }

  manifest = Object.keys(manifest)
    .sort()
    // eslint-disable-next-line no-sequences
    .reduce((a, c) => ((a[c] = manifest[c]), a), {} as any)

  return {
    reactLoadableManifest: manifest,
    dynamicCssManifest: Array.from(dynamicCssManifestSet),
  }
}

export class ReactLoadablePlugin {
  private filename: string
  private pagesOrAppDir: string | undefined
  private isPagesDir: boolean
  private runtimeAsset?: string
  private dev: boolean

  constructor(opts: {
    filename: string
    pagesDir?: string
    appDir?: string
    runtimeAsset?: string
    dev: boolean
  }) {
    this.filename = opts.filename
    this.pagesOrAppDir = opts.pagesDir || opts.appDir
    this.isPagesDir = Boolean(opts.pagesDir)
    this.runtimeAsset = opts.runtimeAsset
    this.dev = opts.dev
  }

  createAssets(compiler: any, compilation: any) {
    const projectSrcDir = this.pagesOrAppDir
      ? path.dirname(this.pagesOrAppDir)
      : undefined
    const shouldCreateDynamicCssManifest = !this.dev && this.isPagesDir
    const { reactLoadableManifest, dynamicCssManifest } = buildManifest(
      compiler,
      compilation,
      projectSrcDir,
      this.dev,
      shouldCreateDynamicCssManifest
    )

    compilation.emitAsset(
      this.filename,
      new sources.RawSource(JSON.stringify(reactLoadableManifest, null, 2))
    )

    if (this.runtimeAsset) {
      compilation.emitAsset(
        this.runtimeAsset,
        new sources.RawSource(
          `self.__REACT_LOADABLE_MANIFEST=${JSON.stringify(
            JSON.stringify(reactLoadableManifest)
          )}`
        )
      )
    }

    // This manifest prevents removing server rendered <link> tags after client
    // navigation. This is only needed under Pages dir && Production && Webpack.
    // x-ref: https://github.com/vercel/next.js/pull/72959
    if (shouldCreateDynamicCssManifest) {
      compilation.emitAsset(
        `${DYNAMIC_CSS_MANIFEST}.json`,
        new sources.RawSource(JSON.stringify(dynamicCssManifest, null, 2))
      )

      // This is for edge runtime.
      compilation.emitAsset(
        `server/${DYNAMIC_CSS_MANIFEST}.js`,
        new sources.RawSource(
          `self.__DYNAMIC_CSS_MANIFEST=${JSON.stringify(
            JSON.stringify(dynamicCssManifest)
          )}`
        )
      )
    }
  }

  apply(compiler: webpack.Compiler) {
    compiler.hooks.make.tap('ReactLoadableManifest', (compilation) => {
      compilation.hooks.processAssets.tap(
        {
          name: 'ReactLoadableManifest',
          stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
        },
        () => {
          this.createAssets(compiler, compilation)
        }
      )
    })
  }
}