Skip to content

Commit

Permalink
feat: add FileToChunkRelationPlugin
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyuang committed Aug 18, 2024
1 parent eca5497 commit f2b956e
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 22 deletions.
7 changes: 1 addition & 6 deletions packages/plugin-vue/src/config/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import * as WebpackChain from 'webpack-chain'
import { getBaseConfig } from './base'

const safePostCssParser = require('postcss-safe-parser')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const generateAnalysis = Boolean(process.env.GENERATE_ANALYSIS)

const loadModule = loadModuleFromFramework

const getClientWebpack = (chain: WebpackChain) => {
Expand Down Expand Up @@ -60,10 +59,6 @@ const getClientWebpack = (chain: WebpackChain) => {
fileName: 'asset-manifest.json'
}])

chain.when(generateAnalysis, chain => {
chain.plugin('analyze').use(BundleAnalyzerPlugin)
})

chainClientConfig(chain) // 合并用户自定义配置

return chain.toConfig()
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-vue3/src/config/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { loadConfig, getOutputPublicPath, loadModuleFromFramework, getSplitChunksOptions, getBuildConfig, terserConfig, asyncChunkMap } from 'ssr-common-utils'
import * as WebpackChain from 'webpack-chain'

import { getBaseConfig } from './base'

const safePostCssParser = require('postcss-safe-parser')
Expand Down
4 changes: 2 additions & 2 deletions packages/plugin-vue3/src/entry/server-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const { FeRoutes, App, layoutFetch, Layout } = Routes
const staticConfig = getStaticConfig()

const serverRender = async (ctx: ISSRContext, config: IConfig) => {
const { mode, customeHeadScript, customeFooterScript, parallelFetch, prefix, isVite, isDev, clientPrefix, stream, fePort, https, rootId, bigpipe, hashRouter, asyncGlobalData } = config
const { mode, customeHeadScript, customeFooterScript, parallelFetch, prefix, isVite, isDev, clientPrefix, stream, rootId, bigpipe, hashRouter, asyncGlobalData } = config
const store = createStore()
const router = createRouter()
const pinia = createPinia()
Expand All @@ -40,7 +40,7 @@ const serverRender = async (ctx: ISSRContext, config: IConfig) => {
}: vue3AppParams) => {
const app = createSSRApp({
render: function () {
const ssrDevInfo = { manifest: isDev ? manifest : '', rootId, fePort: isDev ? fePort : '', https: isDev ? https : '' }
const ssrDevInfo = { manifest: isDev ? manifest : '', rootId }
const innerHTML = splitPageInfo({
'window.__USE_SSR__': !isCsr,
'window.__INITIAL_DATA__': isCsr ? {} : serialize(state),
Expand Down
3 changes: 2 additions & 1 deletion packages/utils/src/server/loadConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,10 @@ const loadConfig = (): IConfig => {
}
const assetsDir = userConfig.assetsDir ?? 'static'
const manifestPath = `${normalizeEndPath(devPublicPath)}asset-manifest.json`
const chunkMapPath = `${normalizeEndPath(devPublicPath)}chunkMap.json`
const staticPath = `${normalizeEndPath(devPublicPath)}${assetsDir}`
const hotUpdatePath = `${normalizeEndPath(devPublicPath)}*.hot-update**`
const proxyKey = [staticPath, hotUpdatePath, manifestPath]
const proxyKey = [staticPath, hotUpdatePath, manifestPath, chunkMapPath]
const prefix = '/'
const dynamicFile = {
serverBundle: join(cwd, `./build/server/${chunkName}.server.js`),
Expand Down
7 changes: 5 additions & 2 deletions packages/utils/src/server/webpack/common-chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { logWarning } from '../log'
import { getPkgMajorVersion } from '../judge'
import { asyncChunkMap } from '../build-utils'
import { nameSpaceBuiltinModules } from '../static'
import { FileToChunkRelationPlugin } from './plugins'

const [antdVersion, vantVersion] = [getPkgMajorVersion('antd'), getPkgMajorVersion('vant')]
const isAntd4 = antdVersion === 4
Expand Down Expand Up @@ -119,7 +120,7 @@ const addBabelLoader = (chain: Rule<Module>, envOptions: any, isServer: boolean)
.end()
}
const addCommonChain = (chain: Chain, isServer: boolean) => {
const { babelOptions, corejsOptions, babelExtraModule, assetsDir, optimize } = loadConfig()
const { babelOptions, corejsOptions, babelExtraModule, assetsDir, optimize, isDev } = loadConfig()
const { publicPath, imagePath } = getImageOutputPath()
const envOptions = {
modules: false,
Expand Down Expand Up @@ -191,7 +192,9 @@ const addCommonChain = (chain: Chain, isServer: boolean) => {
nameSpaceBuiltinModules.forEach(moduleName => {
chain.node.set(moduleName, 'empty')
})

chain.when(isDev, chain => {
chain.plugin('chunkMap').use(FileToChunkRelationPlugin)
})
chain.when(generateAnalysis, chain => {
chain.plugin('analyze').use(BundleAnalyzerPlugin)
})
Expand Down
41 changes: 41 additions & 0 deletions packages/utils/src/server/webpack/plugins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { relative } from 'path'
import type { Compiler } from 'webpack'

interface FileToChunkMap {
[filePath: string]: string
}

export class FileToChunkRelationPlugin {
apply (compiler: Compiler) {
compiler.hooks.emit.tapAsync(
'FileToChunkRelationPlugin',
(compilation, callback) => {
const fileToChunkMap: FileToChunkMap = {}

// Iterate through all chunks
for (const chunk of compilation.chunks) {
// Get all modules for this chunk
const chunkName = chunk.name || chunk.id as string
for (const module of chunk.modulesIterable) {
if (module.resource) {
let source = relative(compiler.context, module.resource)
if (!source.startsWith('.')) {
source = `./${source}`
}
fileToChunkMap[source] = chunkName
}
}
}

// Add the map as a new asset
const content = JSON.stringify(fileToChunkMap, null, 2)
compilation.assets['chunkMap.json'] = {
source: () => content,
size: () => content.length
}

callback()
}
)
}
}
12 changes: 1 addition & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f2b956e

Please sign in to comment.