Skip to content

Commit

Permalink
chore(nuxt3): add more types (nuxt#51)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
  • Loading branch information
danielroe and pi0 authored Apr 4, 2021
1 parent 6c86b22 commit 2db79ad
Show file tree
Hide file tree
Showing 11 changed files with 123 additions and 48 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@rollup/plugin-node-resolve": "^11.2.1",
"@types/jest": "^26.0.22",
"@types/node": "^14.14.37",
"@types/rimraf": "^3.0.0",
"chalk": "^4.1.0",
"defu": "^3.2.2",
"esbuild": "^0.10.0",
Expand Down
8 changes: 7 additions & 1 deletion packages/nuxt3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@
"lodash": "^4.17.21",
"nuxt-cli": "^0.1.1",
"scule": "^0.1.1",
"ufo": "^0.6.10"
"ufo": "^0.6.10",
"upath": "^2.0.1"
},
"devDependencies": {
"@types/fs-extra": "^9.0.10",
"@types/hash-sum": "^1.0.0",
"@types/lodash": "^4.14.168"
}
}
2 changes: 1 addition & 1 deletion packages/nuxt3/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function createApp (
pages: {
dir: 'pages'
}
})
} as NuxtApp)

// Resolve app.main
const resolveOptions = {
Expand Down
9 changes: 5 additions & 4 deletions packages/nuxt3/src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
scanTemplates,
NuxtTemplate
} from './template'
import { createWatcher } from './watch'
import { createWatcher, WatchCallback } from './watch'
import { createApp, NuxtApp } from './app'
import Ignore from './utils/ignore'

Expand All @@ -20,7 +20,7 @@ export class Builder {
templates: NuxtTemplate[]
app: NuxtApp

constructor (nuxt) {
constructor (nuxt: Nuxt) {
this.nuxt = nuxt
this.ignore = new Ignore({
rootDir: nuxt.options.srcDir,
Expand Down Expand Up @@ -65,7 +65,7 @@ function watch (builder: Builder) {

// Watch user app
// TODO: handle multiples app dirs
const appPattern = `${builder.app.dir}/**/*.{${nuxt.options.extensions.join(',')}}`
const appPattern = `${builder.app.dir}/**/*{${nuxt.options.extensions.join(',')}}`
const appWatcher = createWatcher(appPattern, { ...options, cwd: builder.app.dir }, ignore)
// appWatcher.debug('srcDir')
const refreshTemplates = debounce(() => generate(builder), 100)
Expand All @@ -77,7 +77,8 @@ function watch (builder: Builder) {
appWatcher.watch(/^plugins/, refreshTemplates, ['add', 'unlink'])

// Shared Watcher
const watchHookDebounced = debounce((event, file) => builder.nuxt.callHook('builder:watch', event, file), 100)
const watchHook: WatchCallback = (event, path) => builder.nuxt.callHook('builder:watch', event, path)
const watchHookDebounced = debounce(watchHook, 100)
appWatcher.watchAll(watchHookDebounced)
nuxtAppWatcher.watchAll(watchHookDebounced)
}
Expand Down
20 changes: 10 additions & 10 deletions packages/nuxt3/src/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@ export interface NuxtPlugin {
}

const MODES_REGEX = /\.(server|client)(\.\w+)*$/
const getPluginMode = (src) => {
const getPluginMode = (src: string) => {
const [, mode = 'all'] = src.match(MODES_REGEX) || []

return mode
return mode as NuxtPlugin['mode']
}

export function resolvePlugins (builder: Builder, app: NuxtApp) {
return resolveFiles(builder, 'plugins/**/*.{js,ts}', app.dir)
.then(plugins => plugins.map((src) => {
return {
src,
mode: getPluginMode(src)
}
}))
export async function resolvePlugins (builder: Builder, app: NuxtApp) {
const plugins = await resolveFiles(builder, 'plugins/**/*.{js,ts}', app.dir)

return plugins.map(src => ({
src,
mode: getPluginMode(src)
})
)
}
12 changes: 7 additions & 5 deletions packages/nuxt3/src/template.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { join, relative, dirname } from 'path'
import fsExtra from 'fs-extra'
import globby from 'globby'
import lodashTemplate from 'lodash/template'
import { join, relative, dirname } from 'upath'

import * as nxt from './utils/nxt'
import type { Builder } from './builder'

export interface NuxtTemplate {
src: string // Absolute path to source file
path: string // Relative path of destination
data?: any
}

export function templateData (builder) {
export function templateData (builder: Builder) {
return {
globals: builder.globals,
app: builder.app,
Expand All @@ -21,7 +23,7 @@ export function templateData (builder) {

async function compileTemplate (tmpl: NuxtTemplate, destDir: string) {
const srcContents = await fsExtra.readFile(tmpl.src, 'utf-8')
let compiledSrc
let compiledSrc: string
try {
compiledSrc = lodashTemplate(srcContents, {})(tmpl.data)
} catch (err) {
Expand All @@ -38,7 +40,7 @@ export function compileTemplates (templates: NuxtTemplate[], destDir: string) {
return Promise.all(templates.map(t => compileTemplate(t, destDir)))
}

export async function scanTemplates (dir: string, data?: Object) {
export async function scanTemplates (dir: string, data?: Record<string, any>) {
const templateFiles = (await globby(join(dir, '/**')))

return templateFiles.map(src => ({
Expand All @@ -48,7 +50,7 @@ export async function scanTemplates (dir: string, data?: Object) {
}))
}

export function watchTemplate (template: NuxtTemplate, _watcher: any, _cb: Function) {
export function watchTemplate (template: NuxtTemplate, _watcher: any, _cb: () => any) {
template.data = new Proxy(template.data, {
// TODO: deep watch option changes
})
Expand Down
12 changes: 6 additions & 6 deletions packages/nuxt3/src/utils/ignore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,27 @@ export default class Ignore {
}

readIgnoreFile () {
if (this.findIgnoreFile()) {
if (this.findIgnoreFile() && this.ignoreFile) {
return fs.readFileSync(this.ignoreFile, 'utf8')
}
}

addIgnoresRules () {
const content = this.readIgnoreFile()
if (!this.ignore) {
this.ignore = ignore(this.ignoreOptions)
}
if (content) {
this.ignore.add(content)
}
if (this.ignoreArray && this.ignoreArray.length > 0) {
if (!this.ignore) {
this.ignore = ignore(this.ignoreOptions)
}
this.ignore.add(this.ignoreArray)
}
}

filter (paths: string[]) {
filter (paths: string[] = []) {
if (this.ignore) {
return this.ignore.filter([].concat(paths || []))
return this.ignore.filter(([] as string[]).concat(paths))
}
return paths
}
Expand Down
13 changes: 12 additions & 1 deletion packages/nuxt3/src/utils/nxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,18 @@ export const importSources = (sources: string | string[], { lazy = false } = {})
}).join('\n')
}

export const serializeRoute = (route: NuxtRoute) => {
interface SerializedRoute {
name?: string
path: string
children: SerializedRoute[]
/**
* @private
*/
__file: string
component: string
}

export const serializeRoute = (route: NuxtRoute): SerializedRoute => {
return {
name: route.name,
path: route.path,
Expand Down
23 changes: 14 additions & 9 deletions packages/nuxt3/src/watch.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
import chokidar, { WatchOptions } from 'chokidar'
import defu from 'defu'
import consola from 'consola'

import Ignore from './utils/ignore'

export type WatchEvent = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'

export type WatchCallback = (event: WatchEvent, path: string) => void
export type WatchFilter = (event: WatchEvent, path: string) => boolean | null

export function createWatcher (
pattern: string,
options?: WatchOptions,
ignore?: Ignore
) {
const opts = defu(options, {
const opts = defu(options!, {
ignored: [],
ignoreInitial: true
})
const watcher = chokidar.watch(pattern, opts)
const watchAll = (cb: Function, filter?: Function) => {
const watchAll = (cb: WatchCallback, filter?: WatchFilter) => {
watcher.on('all', (event, path: string) => {
if (ignore && ignore.ignores(path)) {
return
}
const _event = { event, path }
if (!filter || filter(_event)) {
cb(_event)
if (!filter || filter(event, path)) {
cb(event, path)
}
})
}

const watch = (pattern: string | RegExp, cb: Function, events?: string[]) =>
watchAll(cb, ({ event, path }) => path.match(pattern) && (!events || events.includes(event)))
const watch = (pattern: string | RegExp, cb: WatchCallback, events?: WatchEvent[]) =>
watchAll(cb, (event, path) => path.match(pattern) && (!events || events.includes(event)))

const debug = (tag: string = '[Watcher]') => {
consola.log(tag, 'Watching ', pattern)
watchAll((e) => {
consola.log(tag, e.event, e.path)
watchAll((event, path) => {
consola.log(tag, event, path)
})
}

Expand Down
25 changes: 14 additions & 11 deletions scripts/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ export async function build (rootDir: string, stub: boolean) {
if (buildOptions.entries) {
if (!Array.isArray(buildOptions.entries)) {
buildOptions.entries = Object.entries(buildOptions.entries)
} ctx.entries.push(...buildOptions.entries.map(entry => resolveEntry(entry)))
}
ctx.entries.push(...buildOptions.entries.map(entry => resolveEntry(entry)))
}
if (pkg.dependencies) {
ctx.externals.push(...Object.keys(pkg.dependencies))
Expand Down Expand Up @@ -84,7 +85,7 @@ export async function build (rootDir: string, stub: boolean) {
return
}

consola.info(chalk.cyan(`Builduing ${pkg.name}`))
consola.info(chalk.cyan(`Building ${pkg.name}`))
if (process.env.DEBUG) {
consola.info(`
${chalk.bold('Root dir:')} ${ctx.rootDir}
Expand All @@ -98,7 +99,7 @@ export async function build (rootDir: string, stub: boolean) {
const usedImports = new Set<string>()
if (rollupOptions) {
const buildResult = await rollup(rollupOptions)
const outputOptions = rollupOptions.output as OutputOptions
const outputOptions = rollupOptions.output
const { output } = await buildResult.write(outputOptions)

for (const entry of output.filter(e => e.type === 'chunk') as OutputChunk[]) {
Expand All @@ -115,6 +116,7 @@ export async function build (rootDir: string, stub: boolean) {
}

// Types
rollupOptions.plugins = rollupOptions.plugins || []
rollupOptions.plugins.push(dts())
const typesBuild = await rollup(rollupOptions)
await typesBuild.write(outputOptions)
Expand Down Expand Up @@ -179,32 +181,33 @@ function resolveEntry (input: string | [string, Partial<BuildEntry>] | Partial<B
let entry: Partial<BuildEntry>
if (typeof input === 'string') {
entry = { name: input }
}
if (Array.isArray(input)) {
} else if (Array.isArray(input)) {
entry = { name: input[0], ...input[1] }
} else {
entry = input
}
entry.input = entry.input ?? resolve(entry.srcDir || 'src', './' + entry.name)
entry.output = entry.output ?? resolve(entry.distDir || 'dist', './' + entry.name)
entry.bundle = entry.bundle ?? !(entry.input.endsWith('/') || entry.name.endsWith('/'))
entry.bundle = entry.bundle ?? !(entry.input.endsWith('/') || entry.name?.endsWith('/'))
entry.format = entry.format ?? 'esm'
return entry as BuildEntry
}

function dumpObject (obj) {
function dumpObject (obj: Record<string, any>) {
return '{ ' + Object.keys(obj).map(key => `${key}: ${JSON.stringify(obj[key])}`).join(', ') + ' }'
}

function getRollupOptions (ctx: BuildContext): RollupOptions | null {
function getRollupOptions (ctx: BuildContext): RollupOptions & { output: OutputOptions & { dir: string }} | null {
const extensions = ['.ts', '.mjs', '.js', '.json']

const r = (...path) => resolve(ctx.rootDir, ...path)
const r = (...path: string[]) => resolve(ctx.rootDir, ...path)

const entries = ctx.entries.filter(e => e.bundle)
if (!entries.length) {
return null
}

return <RollupOptions>{
return {
input: entries.map(e => e.input),

output: {
Expand All @@ -227,7 +230,7 @@ function getRollupOptions (ctx: BuildContext): RollupOptions | null {
},

onwarn (warning, rollupWarn) {
if (!['CIRCULAR_DEPENDENCY'].includes(warning.code)) {
if (!warning.code || !['CIRCULAR_DEPENDENCY'].includes(warning.code)) {
rollupWarn(warning)
}
},
Expand Down
Loading

0 comments on commit 2db79ad

Please sign in to comment.