Skip to content

Commit

Permalink
refactor: split module up into composables/vue/module (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Mar 15, 2021
1 parent f8fdb7f commit c394e35
Show file tree
Hide file tree
Showing 27 changed files with 375 additions and 291 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"require": "./lib/entrypoint.js",
"import": "./lib/entrypoint.es.js"
},
"./templates/*": "./lib/templates/*",
"./": "./"
},
"main": "lib/index.js",
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
10 changes: 10 additions & 0 deletions src/composables/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export { useAsync } from './async'
export { useContext, withContext } from './context'
export { useFetch } from './fetch'
export { globalPlugin, onGlobalSetup, setMetaPlugin } from './hooks'
export { useMeta } from './meta'
export { reqRef, reqSsrRef } from './req-ref'
export { ssrRef, shallowSsrRef, setSSRContext, ssrPromise } from './ssr-ref'
export { useStatic } from './static'
export * from './defineHelpers'
export * from './wrappers'
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
93 changes: 2 additions & 91 deletions src/entrypoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,94 +3,5 @@ import CompositionApi from '@vue/composition-api'

Vue.use(CompositionApi)

export { useAsync } from './async'
export { defineComponent } from './component'
export { useContext, withContext } from './context'
export { useFetch } from './fetch'
export { globalPlugin, onGlobalSetup, setMetaPlugin } from './hooks'
export { useMeta } from './meta'
export { reqRef, reqSsrRef } from './req-ref'
export { ssrRef, shallowSsrRef, setSSRContext, ssrPromise } from './ssr-ref'
export { useStatic } from './static'
export * from './defineHelpers'
export * from './wrappers'

export type {
App,
ComponentInstance,
ComponentRenderProxy,
ComputedGetter,
ComputedRef,
ComputedSetter,
Data,
DeepReadonly,
ExtractDefaultPropTypes,
ExtractPropTypes,
FlushMode,
InjectionKey,
PropOptions,
PropType,
Ref,
SetupContext,
SetupFunction,
ShallowUnwrapRef,
ToRefs,
UnwrapRef,
VueWatcher,
WatchCallback,
WatchEffect,
WatchOptions,
WatchOptionsBase,
WatchSource,
WatchStopHandle,
WritableComputedOptions,
WritableComputedRef,
} from '@vue/composition-api'

export {
computed,
createApp,
createRef,
customRef,
defineAsyncComponent,
del,
getCurrentInstance,
h,
inject,
isRaw,
isReactive,
isReadonly,
isRef,
markRaw,
nextTick,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onServerPrefetch,
onUnmounted,
onUpdated,
provide,
proxyRefs,
reactive,
readonly,
ref,
set,
shallowReactive,
shallowReadonly,
shallowRef,
toRaw,
toRef,
toRefs,
triggerRef,
unref,
useCssModule,
useCSSModule,
version,
warn,
watch,
watchEffect,
} from '@vue/composition-api'
export * from './composables'
export * from './vue'
193 changes: 1 addition & 192 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,194 +1,3 @@
import { resolve, join } from 'upath'
import { withTrailingSlash } from 'ufo'
import { readdirSync, copyFileSync, existsSync, mkdirpSync } from 'fs-extra'

import type { Module, NuxtConfig } from '@nuxt/types'

import { name, version } from '../package.json'

import { compositionApiPlugin } from './vite'

function isFullStatic(options: NuxtConfig) {
return (
!options.dev &&
!options._legacyGenerate &&
options.target === 'static' &&
options.render?.ssr
)
}

function isUrl(url: string) {
return ['http', '//'].some(str => url.startsWith(str))
}

const compositionApiModule: Module<any> = function compositionApiModule() {
let corejsPolyfill = this.nuxt.options.build.corejs
? String(this.nuxt.options.build.corejs)
: undefined
try {
if (!['2', '3'].includes(corejsPolyfill || '')) {
// eslint-disable-next-line
const corejsPkg = this.nuxt.resolver.requireModule('core-js/package.json')
corejsPolyfill = corejsPkg.version.slice(0, 1)
}
} catch {
corejsPolyfill = undefined
}

const libRoot = resolve(__dirname, '..')
const { dst: pluginDst } = this.addTemplate({
src: resolve(libRoot, 'templates', 'plugin.js'),
fileName: join('composition-api', 'plugin.js'),
})

this.addPlugin({
src: resolve(libRoot, 'templates', 'polyfill.client.js'),
fileName: join('composition-api', 'polyfill.client.js'),
options: {
corejsPolyfill,
},
})

const { dst: metaPluginDst } = this.addTemplate({
src: resolve(libRoot, 'templates', 'meta.js'),
fileName: join('composition-api', 'meta.js'),
})

const staticPath = join(this.options.buildDir || '', 'static-json')

this.nuxt.hook('builder:prepared', () => {
mkdirpSync(staticPath)
})

this.nuxt.hook('generate:route', () => {
mkdirpSync(staticPath)
})

this.nuxt.hook('generate:done', async (generator: any) => {
if (!existsSync(staticPath)) return

const { distPath } = generator
readdirSync(staticPath).forEach(file =>
copyFileSync(join(staticPath, file), join(distPath, file))
)
})

const globalName = this.options.globalName || 'nuxt'
const globalContextFactory =
this.options.globals?.context ||
((globalName: string) => `__${globalName.toUpperCase()}__`)
const globalNuxtFactory =
this.options.globals?.nuxt || ((globalName: string) => `$${globalName}`)
const globalContext = globalContextFactory(globalName)
const globalNuxt = globalNuxtFactory(globalName)

const routerBase = withTrailingSlash(this.options.router?.base)
const publicPath = withTrailingSlash(this.options.build?.publicPath)

const { dst: entryDst } = this.addTemplate({
src: resolve(libRoot, 'lib', 'entrypoint.es.js'),
fileName: join('composition-api', 'index.js'),
options: {
isFullStatic: isFullStatic(this.nuxt.options),
staticPath: staticPath,
publicPath: isUrl(publicPath) ? publicPath : routerBase,
globalContext,
globalNuxt,
},
})

const entryFile = resolve(this.options.buildDir || '', entryDst)

this.options.build.transpile = this.options.build.transpile || []
this.options.build.transpile.push('@nuxtjs/composition-api')

if (!this.nuxt.options.dev) {
this.options.build.transpile.push('@vue/composition-api')
}

// Fake alias to prevent shadowing actual node_module
this.options.alias['@nuxtjs/composition-api'] = entryFile

this.nuxt.hook('vite:extend', (ctx: any) => {
ctx.config.plugins.push(compositionApiPlugin())
ctx.config.optimizeDeps.exclude.push('@vue/composition-api')
ctx.config.resolve.alias['~nuxtjs-composition-api'] = entryFile
})

this.options.build = this.options.build || {}
this.options.build.babel = this.options.build.babel || {}

this.options.build.babel.plugins = this.options.build.babel.plugins || []
if (this.options.build.babel.plugins instanceof Function) {
console.warn(
'Unable to automatically add Babel plugin. Make sure your custom `build.babel.plugins` returns `@nuxtjs/composition-api/babel`'
)
} else {
this.options.build.babel.plugins.push(join(__dirname, 'babel'))
}

const actualPresets = this.options.build.babel.presets

this.options.build.babel.presets = (
env,
[defaultPreset, defaultOptions]: [string, Record<string, any>]
) => {
const newOptions = {
...defaultOptions,
jsx: {
...(typeof defaultOptions.jsx === 'object' ? defaultOptions.jsx : {}),
compositionAPI: true,
},
}

if (typeof actualPresets === 'function') {
return actualPresets(env, [defaultPreset, newOptions])
}

return [[defaultPreset, newOptions]]
}

this.options.plugins = this.options.plugins || []
this.options.plugins.unshift(resolve(this.options.buildDir || '', pluginDst))
if (
!(this.nuxt.options.buildModules || []).includes('@nuxtjs/pwa') &&
!this.nuxt.options.modules.includes('@nuxtjs/pwa')
) {
this.options.plugins.push(
resolve(this.options.buildDir || '', metaPluginDst)
)
} else if (this.nuxt.options.dev) {
console.warn(
'useMeta is not supported in onGlobalSetup as @nuxtjs/pwa detected.\nSee https://github.com/nuxt-community/composition-api/issues/307'
)
}
}

// eslint-disable-next-line
// @ts-ignore
compositionApiModule.meta = {
name,
version,
}

const warnToAddModule = () => {
console.error(
'You need to add `@nuxtjs/composition-api` to your buildModules in order to use it. See https://composition-api.nuxtjs.org/getting-started/setup.'
)
throw new Error(
'You need to add `@nuxtjs/composition-api` to your buildModules in order to use it. See https://composition-api.nuxtjs.org/getting-started/setup.'
)
}

const helperFunctions: string[] = JSON.parse(`__HELPER_FUNCTIONS__`)
helperFunctions.forEach(helper => {
// eslint-disable-next-line
// @ts-ignore
compositionApiModule[helper] = warnToAddModule
})

// eslint-disable-next-line
// @ts-ignore
compositionApiModule.defineNuxtConfig = (config: NuxtConfig) => config
import compositionApiModule from './module'

export default compositionApiModule
47 changes: 47 additions & 0 deletions src/module/babel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { NuxtOptions } from '@nuxt/types'
import type { ModuleThis } from '@nuxt/types/config/module'

export function registerBabelPlugin(this: ModuleThis) {
const nuxtOptions: NuxtOptions = this.nuxt.options

/**
* Add Composition API plugin to inject key automatically
*/

nuxtOptions.build.babel = nuxtOptions.build.babel || {}
nuxtOptions.build.babel.plugins = nuxtOptions.build.babel.plugins || []

if (nuxtOptions.build.babel.plugins instanceof Function) {
console.warn(
'Unable to automatically add Babel plugin. Make sure your custom `build.babel.plugins` returns `@nuxtjs/composition-api/babel`'
)
} else {
nuxtOptions.build.babel.plugins.push(
require.resolve('@nuxtjs/composition-api/babel')
)
}

/**
* Opt in to Composition API support in Babel preset
*/

const actualPresets = nuxtOptions.build.babel.presets
nuxtOptions.build.babel.presets = (
env,
[defaultPreset, defaultOptions]: [string, Record<string, any>]
) => {
const newOptions = {
...defaultOptions,
jsx: {
...(typeof defaultOptions.jsx === 'object' ? defaultOptions.jsx : {}),
compositionAPI: true,
},
}

if (typeof actualPresets === 'function') {
return actualPresets(env, [defaultPreset, newOptions])
}

return [[defaultPreset, newOptions]]
}
}
Loading

1 comment on commit c394e35

@vercel
Copy link

@vercel vercel bot commented on c394e35 Mar 15, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.