feat: rewrite as nuxt module

This commit is contained in:
Pooya Parsa 2020-11-05 12:28:39 +01:00
parent 0245bd65de
commit 486c881b2d
7 changed files with 59 additions and 84 deletions

View File

@ -5,12 +5,13 @@ import Hookable from 'hookable'
import prettyBytes from 'pretty-bytes' import prettyBytes from 'pretty-bytes'
import gzipSize from 'gzip-size' import gzipSize from 'gzip-size'
import chalk from 'chalk' import chalk from 'chalk'
import { copy, emptyDir, existsSync, mkdirp } from 'fs-extra' import { emptyDir } from 'fs-extra'
import { getRollupConfig } from './rollup/config' import { getRollupConfig } from './rollup/config'
import { getTargetConfig } from './config' import { getTargetConfig } from './config'
import { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils' import { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils'
export async function build (baseConfig, target) { export async function build (baseConfig, target) {
console.log('\n')
consola.info(`Generating bundle for ${hl(target.target)}`) consola.info(`Generating bundle for ${hl(target.target)}`)
const config: any = getTargetConfig(baseConfig, target) const config: any = getTargetConfig(baseConfig, target)
@ -20,7 +21,7 @@ export async function build (baseConfig, target) {
await hooks.callHook('config', config) await hooks.callHook('config', config)
emptyDir(config.outDir) emptyDir(config.targetDir)
config.rollupConfig = getRollupConfig(config) config.rollupConfig = getRollupConfig(config)
await hooks.callHook('rollup:before', config) await hooks.callHook('rollup:before', config)
@ -34,7 +35,7 @@ export async function build (baseConfig, target) {
) )
for (const tmpl of config.templates) { for (const tmpl of config.templates) {
const dstPath = resolve(config.outDir, tmpl.dst) const dstPath = resolve(config.targetDir, tmpl.dst)
await renderTemplate(tmpl.src, dstPath, { config }) await renderTemplate(tmpl.src, dstPath, { config })
consola.info('Compiled', prettyPath(dstPath)) consola.info('Compiled', prettyPath(dstPath))
} }
@ -48,26 +49,3 @@ export async function compileHTMLTemplate (baseConfig) {
await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS) await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS)
consola.info('Generated', prettyPath(htmlTemplateFileJS)) consola.info('Generated', prettyPath(htmlTemplateFileJS))
} }
export function ensureDist (baseConfig) {
if (!existsSync(resolve(baseConfig.buildDir, 'dist/server'))) {
return consola.error('Please use `nuxt build` first to build project!')
} else {
consola.success('Using existing nuxt build from', prettyPath(baseConfig.buildDir))
}
}
export async function generatePublic (baseConfig) {
await emptyDir(baseConfig.publicDir)
await mkdirp(baseConfig.publicDir)
await copy(
baseConfig.staticDir,
baseConfig.publicDir
)
await copy(
resolve(baseConfig.buildDir, 'dist/client'),
resolve(baseConfig.publicDir, '_nuxt')
)
}

View File

@ -1,27 +0,0 @@
import { resolve } from 'path'
import { build, compileHTMLTemplate, ensureDist, generatePublic } from './build'
import { getBaseConfig } from './config'
export async function runCLI () {
const rootDir = resolve(process.cwd(), process.argv[2] || '.')
// Config
const baseConfig = getBaseConfig(rootDir)
// Ensure dist exists
await ensureDist(baseConfig)
// Compile html template
await compileHTMLTemplate(baseConfig)
// Generate public dir
await generatePublic(baseConfig)
// Bundle for each target
for (const target of baseConfig.targets) {
if (baseConfig.target && target.target !== baseConfig.target) {
continue
}
await build(baseConfig, target)
}
}

View File

@ -2,32 +2,25 @@ import { resolve } from 'path'
import defu from 'defu' import defu from 'defu'
import { tryImport, LIB_DIR } from './utils' import { tryImport, LIB_DIR } from './utils'
export function getBaseConfig (rootDir) { export function getBaseConfig (options) {
let baseConfig = { const baseConfig = {
rootDir, rootDir: options.rootDir,
buildDir: '', buildDir: options.buildDir,
publicDir: '', publicDir: options.generate.dir,
staticDir: '', slsDir: null,
targets: [], targets: [],
templates: [], templates: [],
nuxt: 2, nuxt: 2,
target: process.argv[3] && process.argv[3][0] !== '-' ? process.argv[3] : null, target: null,
minify: process.argv.includes('--minify') ? true : null, minify: null,
analyze: process.argv.includes('--analyze') ? true : null, analyze: null,
logStartup: true logStartup: true,
} ...options.serverless
const nuxtConfig = tryImport(rootDir, './nuxt.config')
if (!nuxtConfig) {
throw new Error('`nuxt.config` file not found in: ' + rootDir)
}
if (nuxtConfig.serverless) {
baseConfig = defu(nuxtConfig.serverless, baseConfig)
} }
baseConfig.buildDir = resolve(baseConfig.rootDir, baseConfig.buildDir || '.nuxt') baseConfig.buildDir = resolve(baseConfig.rootDir, baseConfig.buildDir || '.nuxt')
baseConfig.publicDir = resolve(baseConfig.rootDir, baseConfig.publicDir || 'dist') baseConfig.publicDir = resolve(baseConfig.rootDir, baseConfig.publicDir || 'dist')
baseConfig.staticDir = resolve(baseConfig.rootDir, baseConfig.staticDir || 'static') baseConfig.slsDir = resolve(baseConfig.rootDir, baseConfig.slsDir || '.sls')
baseConfig.targets = baseConfig.targets.map(t => typeof t === 'string' ? { target: t } : t) baseConfig.targets = baseConfig.targets.map(t => typeof t === 'string' ? { target: t } : t)
if (baseConfig.target && !baseConfig.targets.find(t => t.target === baseConfig.target)) { if (baseConfig.target && !baseConfig.targets.find(t => t.target === baseConfig.target)) {
@ -55,7 +48,7 @@ export function getTargetConfig (baseConfig, target) {
_targetDefaults, _targetDefaults,
// Generic defaults // Generic defaults
{ {
outDir: resolve(baseConfig.buildDir, `sls/${target.target}`), targetDir: resolve(baseConfig.slsDir, target.target),
outName: 'index.js' outName: 'index.js'
} }
) )

View File

@ -1 +1,38 @@
export { runCLI } from './cli' import { build, compileHTMLTemplate } from './build'
import { getBaseConfig } from './config'
export default function () {
const { nuxt } = this
if (nuxt.options.dev) {
return
}
// Config
const baseConfig = getBaseConfig(nuxt.options)
if (baseConfig.minify !== false) {
nuxt.options.build._minifyServer = true
}
nuxt.options.build.standalone = true
nuxt.hook('generate:cache:ignore', (ignore) => {
ignore.push(baseConfig.slsDir)
})
nuxt.hook('generate:done', () => buildSLS(baseConfig))
}
async function buildSLS (baseConfig) {
// Compile html template
await compileHTMLTemplate(baseConfig)
// Bundle for each target
for (const target of baseConfig.targets) {
if (baseConfig.target && target.target !== baseConfig.target) {
continue
}
await build(baseConfig, target)
}
}

View File

@ -1,6 +0,0 @@
require('../dist').runCLI().catch((error) => {
const consola = require('consola')
consola.error(error)
process.exit(1)
})

View File

@ -50,7 +50,7 @@ export const getRollupConfig = (config) => {
const options: RollupConfig = { const options: RollupConfig = {
input: config.entry, input: config.entry,
output: { output: {
file: path.resolve(config.outDir, config.outName), file: path.resolve(config.targetDir, config.outName),
format: 'cjs', format: 'cjs',
intro: '', intro: '',
outro: '', outro: '',
@ -77,7 +77,7 @@ export const getRollupConfig = (config) => {
// Dynamic Require Support // Dynamic Require Support
options.plugins.push(dynamicRequire({ options.plugins.push(dynamicRequire({
dir: path.resolve(config.buildDir, 'dist/server'), dir: path.resolve(config.buildDir, 'dist/server'),
outDir: config.node === false ? undefined : config.outDir, outDir: (config.node === false || config.inlineChunks) ? undefined : config.targetDir,
globbyOptions: { globbyOptions: {
ignore: [ ignore: [
'server.js' 'server.js'
@ -123,7 +123,7 @@ export const getRollupConfig = (config) => {
options.plugins.push(analyze()) options.plugins.push(analyze())
} }
if (config.minify) { if (config.minify !== false) {
options.plugins.push(terser()) options.plugins.push(terser())
} }

View File

@ -4,7 +4,7 @@ import { copyFile, mkdirp } from 'fs-extra'
const PLUGIN_NAME = 'dynamic-require' const PLUGIN_NAME = 'dynamic-require'
const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.js` const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.js`
const DYNAMIC_REQUIRE_RE = /require\("\.\/" \+/g const DYNAMIC_REQUIRE_RE = /require\("\.\/" ?\+/g
const TMPL_INLINE = ({ imports }) => const TMPL_INLINE = ({ imports }) =>
`${imports.map(i => `import ${i.name} from '${i.import}'`).join('\n')} `${imports.map(i => `import ${i.name} from '${i.import}'`).join('\n')}