Skip to content
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
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
"express": "^4.16.2",
"htmltidy2": "^0.2.1",
"loadash": "^1.0.0",
"mkdirp-promise": "^5.0.1",
"mz": "^2.7.0",
"ncp": "^2.0.0",
"path-to-regexp": "^2.1.0",
Expand Down
100 changes: 63 additions & 37 deletions src/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ const pathToRegexp = require('path-to-regexp')
const { readFile, exists, writeFile } = require('mz/fs')
const del = require('del')
const { ncp } = require('ncp')
const mkdirp = require('mkdirp-promise')
const { uniq, difference, merge } = require('lodash')
const comboWizard = require('combo-wizard')
const { tidy } = require('htmltidy2')
const portfinder = require('portfinder')
const { fs } = require('mz')

// Default port.
const DEFAULT_PORT = 4848
Expand Down Expand Up @@ -58,15 +58,20 @@ async function main (port, targetPath, options) {

await (() => {
return new Promise(function (resolve, reject) {
ncp(targetPath, sourcePath, {
filter: /^((?!\.tmp_prerender).)*$/ // Ignore .tmp_prerender directory.
}, (err) => {
if (err) {
// LOG.error(err)
reject(err)
ncp(
targetPath,
sourcePath,
{
filter: /^((?!\.tmp_prerender).)*$/ // Ignore .tmp_prerender directory.
},
(err) => {
if (err) {
// LOG.error(err)
reject(err)
}
resolve(true)
}
resolve(true)
})
)
})
})()

Expand All @@ -83,14 +88,16 @@ async function main (port, targetPath, options) {
app.get('*', (req, res) => res.send(index))

// Starting the express server.
server = await (new Promise((resolve, reject) => {
const s = app.listen(port, e => e ? reject(e) : resolve(s))
}))
server = await new Promise((resolve, reject) => {
const s = app.listen(port, (e) => (e ? reject(e) : resolve(s)))
})

LOG.info(`Started server ${HOST}`)

// Launching Puppeteer.
browser = await puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']})
browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
})

LOG.info('Started browser.')

Expand All @@ -107,7 +114,10 @@ async function main (port, targetPath, options) {
// Verify if path is valid in vue-router.
let pathValid = true
if (options.verifyPaths) {
const matched = await page.evaluate((path) => window._vuePrerender.$router.match(path).matched.length, path)
const matched = await page.evaluate(
(path) => window._vuePrerender.$router.match(path).matched.length,
path
)

if (matched === undefined) {
pathValid = true // `vue-router` not found, accept all paths.
Expand Down Expand Up @@ -138,8 +148,8 @@ async function main (port, targetPath, options) {
}

// Check if directory exists, if not create the directory.
if (!(await exists(dir))) {
await mkdirp(dir)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}

// Write the rendered HTML file.
Expand Down Expand Up @@ -208,7 +218,8 @@ async function main (port, targetPath, options) {
}

// Functionality of three main options.
if (options.catchPaths) { // Pre-render pages by catching all links from pages recursively.
if (options.catchPaths) {
// Pre-render pages by catching all links from pages recursively.
let _pages = ['']
let _renderedPages = []

Expand All @@ -219,20 +230,29 @@ async function main (port, targetPath, options) {
await page.goto(`${HOST}/${removeLeadingSlash(path)}`)

// Get the HTML content after Chromium finishes rendering.
const result = await page.evaluate(() => document.documentElement.outerHTML)
const result = await page.evaluate(
() => document.documentElement.outerHTML
)
await savePage(path, result)

// Add current page to the `_renderedPages` array.
_renderedPages = [..._renderedPages, path]

// Set `_pages` with the pages that still need to be rendered.
_pages = difference(
uniq(_pages.concat(result.match(/href="\/[/\w\d-]*"/g).map(s => s.match(/\/([/\w\d-]*)/)[1]))),
uniq(
_pages.concat(
result
.match(/href="\/[/\w\d-]*"/g)
.map((s) => s.match(/\/([/\w\d-]*)/)[1])
)
),
_renderedPages
)
_pages = removeIgnoredPaths(_pages)
} while (_pages.length > 0)
} else if (options.paths && options.paths.length > 0) { // Pre-render a list of pre-defined paths.
} else if (options.paths && options.paths.length > 0) {
// Pre-render a list of pre-defined paths.
let _pages = options.paths
_pages = removeIgnoredPaths(_pages)
let _renderedPages = []
Expand All @@ -243,13 +263,16 @@ async function main (port, targetPath, options) {
await page.goto(`${HOST}/${removeLeadingSlash(path)}`)

// Get the HTML content after Chromium finishes rendering.
const result = await page.evaluate(() => document.documentElement.outerHTML)
const result = await page.evaluate(
() => document.documentElement.outerHTML
)
await savePage(path, result)

_renderedPages.push(path)
}
}
} else if (options.parseRouter) { // Pre-render pages by parsing the `vue-router` options.
} else if (options.parseRouter) {
// Pre-render pages by parsing the `vue-router` options.
// Requesting the index page.
await page.goto(`${HOST}/`)

Expand Down Expand Up @@ -279,13 +302,17 @@ async function main (port, targetPath, options) {

let pathsSet = true
if (paths === 'GLOBAL_VAR_UNDEFINED') {
LOG.error('Global `window._vuePrerender` variable not defined (please refer to the documentation).')
LOG.error(
'Global `window._vuePrerender` variable not defined (please refer to the documentation).'
)
pathsSet = false
} else if (paths === 'ROUTER_UNDEFINED') {
LOG.error('`vue-router` not defined.')
pathsSet = false
} else if (paths === 'ROUTER_NOT_HISTORY_MODE') {
LOG.error('`vue-router` not in `history` mode (please refer to the documentation).')
LOG.error(
'`vue-router` not in `history` mode (please refer to the documentation).'
)
pathsSet = false
}

Expand Down Expand Up @@ -337,7 +364,9 @@ async function main (port, targetPath, options) {
}
}
} else {
LOG.error('Pre-rendering couldn\'t be started because these three configuration options are all set to false: `parseRouter`, `paths`, `catchPaths`. Please refer to the documentation.')
LOG.error(
"Pre-rendering couldn't be started because these three configuration options are all set to false: `parseRouter`, `paths`, `catchPaths`. Please refer to the documentation."
)
}

// Close Chromium and the express server.
Expand Down Expand Up @@ -369,7 +398,12 @@ const _defaultOptions = {
}

const _parseOptions = function (options) {
if (options.logLevel !== 0 && options.logLevel !== 1 && options.logLevel !== 2 && options.logLevel !== 3) {
if (
options.logLevel !== 0 &&
options.logLevel !== 1 &&
options.logLevel !== 2 &&
options.logLevel !== 3
) {
options.logLevel = 0
}

Expand Down Expand Up @@ -415,15 +449,6 @@ const _parseOptions = function (options) {
// All strings and numbers at any level will be converted to an array with just that value in the array.
// Objects are parsed until the last level, where a blank array will be set if there is no string, number or array.
// Proper arrays will be set as the data set.
const _checkArray = (_arr) => {
for (const i in _arr) {
if (_arr[i] === '') {
_arr[i] = undefined
}
}

return _arr
}

if (!(options.paths instanceof Array)) {
if (typeof options.paths === 'string') {
Expand Down Expand Up @@ -455,7 +480,8 @@ const _vuePrerender = function (targetPath, _options, cb) {

// Run the main function.
portfinder.basePort = DEFAULT_PORT
portfinder.getPortPromise()
portfinder
.getPortPromise()
.then((port) => {
main(port, targetPath, options)
.then(() => {
Expand All @@ -466,7 +492,7 @@ const _vuePrerender = function (targetPath, _options, cb) {
cb()
}
})
.catch(err => {
.catch((err) => {
LOG.error(err)

// Close Chromium and the express server.
Expand Down
16 changes: 5 additions & 11 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3833,24 +3833,18 @@ minimist@~0.0.1:
version "0.0.10"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf"

mkdirp-promise@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/mkdirp-promise/-/mkdirp-promise-5.0.1.tgz#e9b8f68e552c68a9c1713b84883f7a1dd039b8a1"
mkdirp@0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.0.tgz#1d73076a6df986cd9344e15e71fcc05a4c9abf12"
dependencies:
mkdirp "*"
minimist "0.0.8"

mkdirp@*, mkdirp@0.5.x, "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.0:
mkdirp@0.5.x, "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.0:
version "0.5.1"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
dependencies:
minimist "0.0.8"

mkdirp@0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.0.tgz#1d73076a6df986cd9344e15e71fcc05a4c9abf12"
dependencies:
minimist "0.0.8"

ms@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
Expand Down