Nuxt/packages/nuxt3/src/webpack/plugins/vue/server.ts

82 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-08-17 18:44:24 +00:00
import { Compilation } from 'webpack'
2020-07-02 13:02:35 +00:00
import { validate, isJS, extractQueryPartJS } from './util'
export default class VueSSRServerPlugin {
2020-08-17 18:44:24 +00:00
options: {
filename?: string
}
2020-07-02 13:02:35 +00:00
constructor (options = {}) {
this.options = Object.assign({
filename: null
}, options)
}
apply (compiler) {
validate(compiler)
compiler.hooks.make.tap('VueSSRServerPlugin', (compilation: any) => {
2020-08-17 18:44:24 +00:00
compilation.hooks.processAssets.tapAsync({
name: 'VueSSRServerPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
}, (assets, cb) => {
const stats = compilation.getStats().toJson()
const [entryName] = Object.keys(stats.entrypoints)
const entryInfo = stats.entrypoints[entryName]
2020-07-02 13:02:35 +00:00
if (!entryInfo) {
// #5553
return cb()
}
2020-07-02 13:02:35 +00:00
const entryAssets = entryInfo.assets.filter(isJS)
2020-07-02 13:02:35 +00:00
if (entryAssets.length > 1) {
throw new Error(
'Server-side bundle should have one single entry file. ' +
'Avoid using CommonsChunkPlugin in the server config.'
)
}
2020-07-02 13:02:35 +00:00
const [entry] = entryAssets
if (!entry || typeof entry !== 'string') {
throw new Error(
`Entry "${entryName}" not found. Did you specify the correct entry option?`
)
}
2020-07-02 13:02:35 +00:00
const bundle = {
entry,
files: {},
maps: {}
}
2020-07-02 13:02:35 +00:00
stats.assets.forEach((asset) => {
if (isJS(asset.name)) {
const queryPart = extractQueryPartJS(asset.name)
if (queryPart !== undefined) {
bundle.files[asset.name] = asset.name.replace(queryPart, '')
} else {
bundle.files[asset.name] = asset.name
}
} else if (asset.name.match(/\.js\.map$/)) {
bundle.maps[asset.name.replace(/\.map$/, '')] = asset.name
2020-07-02 13:02:35 +00:00
} else {
// Do not emit non-js assets for server
delete assets[asset.name]
2020-07-02 13:02:35 +00:00
}
})
2020-07-02 13:02:35 +00:00
const src = JSON.stringify(bundle, null, 2)
2020-07-02 13:02:35 +00:00
assets[this.options.filename] = {
source: () => src,
size: () => src.length
}
2020-07-02 13:02:35 +00:00
cb()
})
2020-08-17 18:44:24 +00:00
})
2020-07-02 13:02:35 +00:00
}
}