Skip to content

[WIP] Add modern mode #199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 53 additions & 37 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,50 +21,66 @@ module.exports = (api, options) => {
api.registerCommand('ssr:build', {
description: 'build for production (SSR)',
}, async (args) => {
const webpack = require('webpack')
const rimraf = require('rimraf')
const formatStats = require('@vue/cli-service/lib/commands/build/formatStats')

const options = service.projectOptions

rimraf.sync(api.resolve(config.distPath))

const { getWebpackConfigs } = require('./lib/webpack')
const [clientConfig, serverConfig] = getWebpackConfigs(service)

const compiler = webpack([clientConfig, serverConfig])
const onCompilationComplete = (err, stats) => {
if (err) {
// eslint-disable-next-line
console.error(err.stack || err)
if (err.details) {
// eslint-disable-next-line
console.error(err.details)
const [clientConfigLegacy, clientConfigModern, serverConfig] = getWebpackConfigs(service)

const compile = ({ webpackConfigs, watch, service }) => {
Object.keys(require.cache)
.filter(key => key.includes('@vue/cli-plugin-babel'))
.forEach(key => delete require.cache[key])

const webpack = require('webpack')
const formatStats = require('@vue/cli-service/lib/commands/build/formatStats')

const options = service.projectOptions

const compiler = webpack(webpackConfigs)
return new Promise((resolve) => {
const onCompilationComplete = (err, stats) => {
if (err) {
// eslint-disable-next-line
console.error(err.stack || err)
if (err.details) {
// eslint-disable-next-line
console.error(err.details)
}
return resolve()
}

if (stats.hasErrors()) {
stats.toJson().errors.forEach(err => console.error(err))
process.exitCode = 1
}

if (stats.hasWarnings()) {
stats.toJson().warnings.forEach(warn => console.warn(warn))
}

try {
// eslint-disable-next-line
console.log(formatStats(stats, options.outputDir, api));
} catch (e) {
}
resolve()
}
return
}

if (stats.hasErrors()) {
stats.toJson().errors.forEach(err => console.error(err))
process.exitCode = 1
}

if (stats.hasWarnings()) {
stats.toJson().warnings.forEach(warn => console.warn(warn))
}

try {
// eslint-disable-next-line
console.log(formatStats(stats, options.outputDir, api));
} catch (e) {
}
}

if (args.watch) {
compiler.watch({}, onCompilationComplete)
} else {
compiler.run(onCompilationComplete)
if (watch) {
compiler.watch({}, onCompilationComplete)
} else {
compiler.run(onCompilationComplete)
}
})
}

process.env.VUE_CLI_MODERN_MODE = true
await compile({ webpackConfigs: [clientConfigLegacy, serverConfig], watch: args.watch, service })
process.env.VUE_CLI_MODERN_BUILD = true
// Modern build depends on files from legacy build, that's why these
// compilations cannot run parallely
await compile({ webpackConfigs: [clientConfigModern], watch: args.watch, service })
})

api.registerCommand('ssr:serve', {
Expand Down
5 changes: 5 additions & 0 deletions lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ module.exports = (app, options) => {
renderer.renderToString(context, (err, renderedHtml) => {
let html = renderedHtml

// Unfortunately, both vue template renderer *and*
// vue-cli ModernModePlugin inject script tags into the html, so
// the former ones are now being removed again
html = html.replace(/<script src="[^"]+" defer><\/script>/g, '')

if (err || context.httpCode === 500) {
console.error(`error during render url : ${req.url}`)

Expand Down
14 changes: 7 additions & 7 deletions lib/dev-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ module.exports.setupDevServer = ({ server, templatePath, onUpdate }) => new Prom
// Read file in real or virtual file systems
const readFile = (fs, file) => {
try {
return fs.readFileSync(path.join(clientConfig.output.path, file), 'utf-8')
return fs.readFileSync(path.join(clientConfigLegacy.output.path, file), 'utf-8')
} catch (e) {}
}

const { getWebpackConfigs } = require('./webpack')
const [clientConfig, serverConfig] = getWebpackConfigs(service)
const [clientConfigLegacy, _, serverConfig] = getWebpackConfigs(service)

let serverBundle
let template
Expand All @@ -43,15 +43,15 @@ module.exports.setupDevServer = ({ server, templatePath, onUpdate }) => new Prom
}

// modify client config to work with hot middleware
clientConfig.entry.app = ['webpack-hot-middleware/client', ...clientConfig.entry.app]
clientConfig.plugins.push(
clientConfigLegacy.entry.app = ['webpack-hot-middleware/client', ...clientConfigLegacy.entry.app]
clientConfigLegacy.plugins.push(
new webpack.HotModuleReplacementPlugin(),
)

// dev middleware
const clientCompiler = webpack(clientConfig)
const clientCompiler = webpack(clientConfigLegacy)
const devMiddleware = require('webpack-dev-middleware')(clientCompiler, {
publicPath: clientConfig.output.publicPath,
publicPath: clientConfigLegacy.output.publicPath,
noInfo: true,
stats: 'none',
logLevel: 'error',
Expand All @@ -72,7 +72,7 @@ module.exports.setupDevServer = ({ server, templatePath, onUpdate }) => new Prom
if (stats.hasErrors()) return

// Fix dev server render error when a custom path is used for the server-renderer bundles
const ssrPlugin = (clientConfig.plugins.find((p) => (p.__pluginName || p.constructor.name) === 'ssr') || {}).options || {}
const ssrPlugin = (clientConfigLegacy.plugins.find((p) => (p.__pluginName || p.constructor.name) === 'ssr') || {}).options || {}

clientManifest = JSON.parse(readFile(
devMiddleware.fileSystem,
Expand Down
57 changes: 42 additions & 15 deletions lib/webpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ exports.chainWebpack = (webpackConfig) => {
if (!target) return
const isClient = target === 'client'
const isProd = process.env.NODE_ENV === 'production'
const modernMode = !!process.env.VUE_CLI_MODERN_MODE
const modernBuild = !!process.env.VUE_CLI_MODERN_BUILD

// Remove unneeded plugins
webpackConfig.plugins.delete('hmr')
Expand Down Expand Up @@ -70,14 +72,37 @@ exports.chainWebpack = (webpackConfig) => {

if (isClient) {
webpackConfig.plugin('ssr').use(VueSSRClientPlugin)
webpackConfig.plugin('loader').use(WebpackBar, [{ name: 'Client', color: 'green' }])

webpackConfig.devtool(!isProd ? '#cheap-module-source-map' : undefined)

webpackConfig.module.rule('vue').use('vue-loader').tap(options => {
options.optimizeSSR = false
return options
})

if (modernMode) {
const ModernModePlugin = require('@vue/cli-service/lib/webpack/ModernModePlugin')
const targetDir = webpackConfig.output.get('path')
if (!modernBuild) {
webpackConfig.plugin('loader').use(WebpackBar, [{ name: 'Client (legacy)', color: 'green' }])

webpackConfig.plugin('modern-mode-legacy').use(ModernModePlugin, [{
isModernBuild: false,
targetDir,

}])
} else {
webpackConfig.plugin('loader').use(WebpackBar, [{ name: 'Client (modern)', color: 'lightgreen' }])

webpackConfig.plugin('modern-mode-modern').use(ModernModePlugin, [{
isModernBuild: true,
targetDir,
jsDirectory: 'js',
}])
}
} else {
webpackConfig.plugin('loader').use(WebpackBar, [{ name: 'Client', color: 'green' }])
}
} else {
webpackConfig.plugin('ssr').use(VueSSRServerPlugin)
webpackConfig.plugin('loader').use(WebpackBar, [{ name: 'Server', color: 'orange' }])
Expand All @@ -89,20 +114,16 @@ exports.chainWebpack = (webpackConfig) => {

webpackConfig.node.clear()

if (!isClient) {
webpackConfig.module.rule('vue').use('cache-loader').tap(options => {
// Change cache directory for server-side
options.cacheIdentifier += '-server'
options.cacheDirectory += '-server'
return options
})
}
webpackConfig.module.rule('vue').use('cache-loader').tap(options => {
// Change cache directory for server-side
options.cacheIdentifier += '-server'
options.cacheDirectory += '-server'
return options
})

webpackConfig.module.rule('vue').use('vue-loader').tap(options => {
if (!isClient) {
options.cacheIdentifier += '-server'
options.cacheDirectory += '-server'
}
options.cacheIdentifier += '-server'
options.cacheDirectory += '-server'
options.optimizeSSR = !isClient
return options
})
Expand All @@ -112,8 +133,14 @@ exports.chainWebpack = (webpackConfig) => {
exports.getWebpackConfigs = (service) => {
process.env.VUE_CLI_MODE = service.mode
process.env.VUE_CLI_SSR_TARGET = 'client'
const clientConfig = service.resolveWebpackConfig()
process.env.VUE_CLI_MODERN_MODE = true
delete process.env.VUE_CLI_MODERN_BUILD
const clientConfigLegacy = service.resolveWebpackConfig()
process.env.VUE_CLI_MODERN_BUILD = true
const clientConfigModern = service.resolveWebpackConfig()
delete process.env.VUE_CLI_MODERN_MODE
delete process.env.VUE_CLI_MODERN_BUILD
process.env.VUE_CLI_SSR_TARGET = 'server'
const serverConfig = service.resolveWebpackConfig()
return [clientConfig, serverConfig]
return [clientConfigLegacy, clientConfigModern, serverConfig]
}