Nuxt/packages/core/src/module.js

206 lines
5.6 KiB
JavaScript
Raw Normal View History

2018-03-16 16:12:06 +00:00
import path from 'path'
import fs from 'fs'
import hash from 'hash-sum'
import consola from 'consola'
2018-12-22 21:05:13 +00:00
import { chainFn, sequence } from '@nuxt/utils'
2017-05-11 10:59:08 +00:00
2018-03-16 16:12:06 +00:00
export default class ModuleContainer {
constructor (nuxt) {
2017-05-11 10:04:15 +00:00
this.nuxt = nuxt
2017-05-11 10:59:08 +00:00
this.options = nuxt.options
2018-01-11 13:28:45 +00:00
this.requiredModules = {}
2020-06-03 19:34:10 +00:00
// Self bind to allow destructre from container
for (const method of Object.getOwnPropertyNames(ModuleContainer.prototype)) {
if (typeof this[method] === 'function') {
this[method] = this[method].bind(this)
}
}
2017-07-17 19:26:41 +00:00
}
async ready () {
2018-01-11 13:28:45 +00:00
// Call before hook
2017-10-31 11:45:32 +00:00
await this.nuxt.callHook('modules:before', this, this.options.modules)
2018-01-11 13:28:45 +00:00
if (this.options.buildModules && !this.options._start) {
// Load every devModule in sequence
2020-06-03 19:34:10 +00:00
await sequence(this.options.buildModules, this.addModule)
}
2017-10-30 17:41:22 +00:00
// Load every module in sequence
2020-06-03 19:34:10 +00:00
await sequence(this.options.modules, this.addModule)
// Load ah-hoc modules last
await sequence(this.options._modules, this.addModule)
2018-01-11 13:28:45 +00:00
2017-10-30 21:39:08 +00:00
// Call done hook
await this.nuxt.callHook('modules:done', this)
2017-05-11 10:59:08 +00:00
}
addVendor () {
consola.warn('addVendor has been deprecated due to webpack4 optimization')
2017-05-11 10:59:08 +00:00
}
addTemplate (template) {
2018-01-11 15:13:52 +00:00
if (!template) {
throw new Error('Invalid template: ' + JSON.stringify(template))
2017-05-11 10:59:08 +00:00
}
2018-01-11 13:28:45 +00:00
// Validate & parse source
const src = template.src || template
const srcPath = path.parse(src)
2018-08-03 15:06:18 +00:00
if (typeof src !== 'string' || !fs.existsSync(src)) {
throw new Error('Template src not found: ' + src)
2017-05-11 10:59:08 +00:00
}
2018-01-11 13:28:45 +00:00
feat: options.target and full-static export (#6159) * feat: add options.target * fix(lint): lint * fix(test): update snapshots * fix(builder): default value for target * fix(test): fix test * fix(test): test fixing * fix: use this.options.target * fix: final test * Update packages/vue-renderer/src/renderer.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * feat: Add target option and update banner * fix(lint): fix * feat: Add warning when using serverMiddleware in static target * chore(utils): add TARGETS and MODES as constants * hotfix: lint * chore(module): add filename as alias of fileName * feat: introducing nuxt export and router/routes.json * hotfix: Fix the linting lord * chore(core): add comment for filename vs fileName * fix: use targets constant * chore: remove warning * fix: unit testing * wip: refactor and use TARGETS * fix: lint * feat: add target as alias for first arg value * fix: generate only for SPA * chore: explain to use nuxt static X * fix: render SPA fallback on redirect for static target * fix: lint issue * fix: only target is useful for now * wip * wip: nuxt static export is looking good * Update packages/generator/src/generator.js Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com> * Update packages/cli/src/options/common.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * feat: add options.target * fix(lint): lint * fix(test): update snapshots * fix(builder): default value for target * fix(test): fix test * fix(test): test fixing * fix: use this.options.target * fix: final test * Update packages/vue-renderer/src/renderer.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * feat: Add target option and update banner * fix(lint): fix * feat: Add warning when using serverMiddleware in static target * chore(utils): add TARGETS and MODES as constants * hotfix: lint * chore(module): add filename as alias of fileName * feat: introducing nuxt export and router/routes.json * hotfix: Fix the linting lord * chore(core): add comment for filename vs fileName * fix: use targets constant * chore: remove warning * fix: unit testing * wip: refactor and use TARGETS * fix: lint * feat: add target as alias for first arg value * chore: explain to use nuxt static X * fix: render SPA fallback on redirect for static target * fix: lint issue * fix: only target is useful for now * wip * wip: nuxt static export is looking good * Update packages/generator/src/generator.js Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com> * Update packages/cli/src/options/common.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * fix: duplicate imports * chore: don't server render if an error happens on static target * test: update unit and add export * lint: fix * lint: fix * fix: e2e test * fix: fallback only for static target * fix: dev test * feat: add generate.crawler * fix: full static is when generate.static is given * chore: improvements * fix: Add isFullStatic in nuxt/config.json * feat: handle fetch for full static * feat: router.prefetchPayloads for full static * chore: use fetch in async-data example * fix: add target only if given * fix: use created to have access to props in fetchOnServer * chore: add console.error in dev for easy debugging * feat: payload smart pre-fetching * fix: remove alias for target * fix: increment payloadFetchIndex is static set to false * chore: lint * chore: add serve command * chore: rename universal to server-side * fix: handle payloadPath on SPA fallback * fix: lint * chore lint again * feat: handle spa fallback * feat: support string for exclude * fix: fallback only if no extension or html * chore: use JSON.stringify() for static target * chore: lint again, dammit * chore: fix tests and remove too early return * fix: early return only for server target * fix: update tests * fix: unit tests * chore: add ssr option * chore: add logic for ssr option * fix: #6682 * chore(dx): add next command to run * fix: lint * fix: tests * chore: keep old behaviour for nuxt build in spa * fix: test again, oh boy * fix: alright this is good now * chore: add comment for spa fallback * chore: move routes.json to dot nuxt dir * chore: simplify check for promise * chore: unique lock id * chore: refactor isFullStatic * fix: dont set default in build context * chore: add test for serve * chore: update tests * hotfix: lint tests * chore(dx): improve message for bundling * feat: js payload extraction with jsonp * fix: keep serialized session script for legacy generate * fix: call to setPagePayload from fetchPayload * use devalue for payload chunks * feat: add initial load state chunk * feat: preload payload and state scripts * fix(vue-app): don't re-render the app if trailing slash on SSG * hotfix: remove console.log * chore(dx): add deploy infos for nuxt export Co-authored-by: Pooya Parsa <pyapar@gmail.com> * chore: handle fetching payload.js for nuxt state * chore(dx): error when using nuxt generate and static * chore: remove static option for clarity * chore: remove serverless target * hotfix: lint * hotfix: unit tests * chore: update legacy js resource * chore: remove query params from url in static target * fix: use globalName and urlJoin * chore: typo * feat: previewMode 👀 * chore: rename to enablePreview * fix: wait next tick to avoid error on spa * chore: try 1 sec * hotfix: test only for linux, wtf azure * refactor: static assets - generalize logic for modules need emit export static assets - allow customization for version, dir and base - serialization logic is only in ssr now * feat: smart state chunk creates * fix(client): ignore payload load error * perf: avoide payload loading for spa initial * perf: avoid loading failed chunks again * chore(cli): add simple compression for nuxt serve * test: update snapshots * fix version snapshot * fix(generator): set staticAssetsBase on context only for full static * fix tests * fix: honor shouldHashCspScriptSrc * chore(dx): add log for client-side fallback creation Co-authored-by: Xin Du (Clark) <clark.duxin@gmail.com> Co-authored-by: Alexander Lichter <manniL@gmx.net> Co-authored-by: Pooya Parsa <pooya@pi0.ir> Co-authored-by: Devon Rueckner <indirectlylit@users.noreply.github.com> Co-authored-by: Pooya Parsa <pyapar@gmail.com>
2020-05-07 19:08:01 +00:00
// Mostly for DX, some people prefers `filename` vs `fileName`
const fileName = template.fileName || template.filename
// Generate unique and human readable dst filename if not provided
const dst = fileName || `${path.basename(srcPath.dir)}.${srcPath.name}.${hash(src)}${srcPath.ext}`
// Add to templates list
const templateObj = {
src,
dst,
options: template.options
2017-05-11 10:59:08 +00:00
}
2018-01-11 13:28:45 +00:00
2017-05-11 18:47:53 +00:00
this.options.build.templates.push(templateObj)
feat: options.target and full-static export (#6159) * feat: add options.target * fix(lint): lint * fix(test): update snapshots * fix(builder): default value for target * fix(test): fix test * fix(test): test fixing * fix: use this.options.target * fix: final test * Update packages/vue-renderer/src/renderer.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * feat: Add target option and update banner * fix(lint): fix * feat: Add warning when using serverMiddleware in static target * chore(utils): add TARGETS and MODES as constants * hotfix: lint * chore(module): add filename as alias of fileName * feat: introducing nuxt export and router/routes.json * hotfix: Fix the linting lord * chore(core): add comment for filename vs fileName * fix: use targets constant * chore: remove warning * fix: unit testing * wip: refactor and use TARGETS * fix: lint * feat: add target as alias for first arg value * fix: generate only for SPA * chore: explain to use nuxt static X * fix: render SPA fallback on redirect for static target * fix: lint issue * fix: only target is useful for now * wip * wip: nuxt static export is looking good * Update packages/generator/src/generator.js Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com> * Update packages/cli/src/options/common.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * feat: add options.target * fix(lint): lint * fix(test): update snapshots * fix(builder): default value for target * fix(test): fix test * fix(test): test fixing * fix: use this.options.target * fix: final test * Update packages/vue-renderer/src/renderer.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * feat: Add target option and update banner * fix(lint): fix * feat: Add warning when using serverMiddleware in static target * chore(utils): add TARGETS and MODES as constants * hotfix: lint * chore(module): add filename as alias of fileName * feat: introducing nuxt export and router/routes.json * hotfix: Fix the linting lord * chore(core): add comment for filename vs fileName * fix: use targets constant * chore: remove warning * fix: unit testing * wip: refactor and use TARGETS * fix: lint * feat: add target as alias for first arg value * chore: explain to use nuxt static X * fix: render SPA fallback on redirect for static target * fix: lint issue * fix: only target is useful for now * wip * wip: nuxt static export is looking good * Update packages/generator/src/generator.js Co-Authored-By: Devon Rueckner <indirectlylit@users.noreply.github.com> * Update packages/cli/src/options/common.js Co-Authored-By: Alexander Lichter <manniL@gmx.net> * fix: duplicate imports * chore: don't server render if an error happens on static target * test: update unit and add export * lint: fix * lint: fix * fix: e2e test * fix: fallback only for static target * fix: dev test * feat: add generate.crawler * fix: full static is when generate.static is given * chore: improvements * fix: Add isFullStatic in nuxt/config.json * feat: handle fetch for full static * feat: router.prefetchPayloads for full static * chore: use fetch in async-data example * fix: add target only if given * fix: use created to have access to props in fetchOnServer * chore: add console.error in dev for easy debugging * feat: payload smart pre-fetching * fix: remove alias for target * fix: increment payloadFetchIndex is static set to false * chore: lint * chore: add serve command * chore: rename universal to server-side * fix: handle payloadPath on SPA fallback * fix: lint * chore lint again * feat: handle spa fallback * feat: support string for exclude * fix: fallback only if no extension or html * chore: use JSON.stringify() for static target * chore: lint again, dammit * chore: fix tests and remove too early return * fix: early return only for server target * fix: update tests * fix: unit tests * chore: add ssr option * chore: add logic for ssr option * fix: #6682 * chore(dx): add next command to run * fix: lint * fix: tests * chore: keep old behaviour for nuxt build in spa * fix: test again, oh boy * fix: alright this is good now * chore: add comment for spa fallback * chore: move routes.json to dot nuxt dir * chore: simplify check for promise * chore: unique lock id * chore: refactor isFullStatic * fix: dont set default in build context * chore: add test for serve * chore: update tests * hotfix: lint tests * chore(dx): improve message for bundling * feat: js payload extraction with jsonp * fix: keep serialized session script for legacy generate * fix: call to setPagePayload from fetchPayload * use devalue for payload chunks * feat: add initial load state chunk * feat: preload payload and state scripts * fix(vue-app): don't re-render the app if trailing slash on SSG * hotfix: remove console.log * chore(dx): add deploy infos for nuxt export Co-authored-by: Pooya Parsa <pyapar@gmail.com> * chore: handle fetching payload.js for nuxt state * chore(dx): error when using nuxt generate and static * chore: remove static option for clarity * chore: remove serverless target * hotfix: lint * hotfix: unit tests * chore: update legacy js resource * chore: remove query params from url in static target * fix: use globalName and urlJoin * chore: typo * feat: previewMode 👀 * chore: rename to enablePreview * fix: wait next tick to avoid error on spa * chore: try 1 sec * hotfix: test only for linux, wtf azure * refactor: static assets - generalize logic for modules need emit export static assets - allow customization for version, dir and base - serialization logic is only in ssr now * feat: smart state chunk creates * fix(client): ignore payload load error * perf: avoide payload loading for spa initial * perf: avoid loading failed chunks again * chore(cli): add simple compression for nuxt serve * test: update snapshots * fix version snapshot * fix(generator): set staticAssetsBase on context only for full static * fix tests * fix: honor shouldHashCspScriptSrc * chore(dx): add log for client-side fallback creation Co-authored-by: Xin Du (Clark) <clark.duxin@gmail.com> Co-authored-by: Alexander Lichter <manniL@gmx.net> Co-authored-by: Pooya Parsa <pooya@pi0.ir> Co-authored-by: Devon Rueckner <indirectlylit@users.noreply.github.com> Co-authored-by: Pooya Parsa <pyapar@gmail.com>
2020-05-07 19:08:01 +00:00
return templateObj
}
addPlugin (template) {
2017-06-11 14:17:36 +00:00
const { dst } = this.addTemplate(template)
2018-01-11 13:28:45 +00:00
// Add to nuxt plugins
this.options.plugins.unshift({
2017-06-11 14:17:36 +00:00
src: path.join(this.options.buildDir, dst),
2018-12-20 09:28:10 +00:00
// TODO: remove deprecated option in Nuxt 3
ssr: template.ssr,
mode: template.mode
})
2017-05-11 10:59:08 +00:00
}
addLayout (template, name) {
2018-02-07 11:58:48 +00:00
const { dst, src } = this.addTemplate(template)
const layoutName = name || path.parse(src).name
const layout = this.options.layouts[layoutName]
if (layout) {
consola.warn(`Duplicate layout registration, "${layoutName}" has been registered as "${layout}"`)
}
2018-02-07 11:58:48 +00:00
2018-02-14 19:31:11 +00:00
// Add to nuxt layouts
this.options.layouts[layoutName] = `./${dst}`
// If error layout, set ErrorPage
if (name === 'error') {
this.addErrorLayout(dst)
}
}
addErrorLayout (dst) {
const relativeBuildDir = path.relative(this.options.rootDir, this.options.buildDir)
this.options.ErrorPage = `~/${relativeBuildDir}/${dst}`
2018-02-07 11:58:48 +00:00
}
addServerMiddleware (middleware) {
2017-05-19 09:14:24 +00:00
this.options.serverMiddleware.push(middleware)
}
extendBuild (fn) {
2017-05-12 07:57:24 +00:00
this.options.build.extend = chainFn(this.options.build.extend, fn)
}
extendRoutes (fn) {
2018-01-11 13:28:45 +00:00
this.options.router.extendRoutes = chainFn(
this.options.router.extendRoutes,
fn
)
2017-05-11 10:59:08 +00:00
}
requireModule (moduleOpts) {
2020-05-18 11:58:48 +00:00
return this.addModule(moduleOpts)
}
2020-05-18 11:58:48 +00:00
async addModule (moduleOpts) {
2018-01-11 13:28:45 +00:00
let src
let options
let handler
// Type 1: String or Function
if (typeof moduleOpts === 'string' || typeof moduleOpts === 'function') {
2018-01-11 13:28:45 +00:00
src = moduleOpts
2018-01-11 15:13:52 +00:00
} else if (Array.isArray(moduleOpts)) {
// Type 2: Babel style array
[src, options] = moduleOpts
2018-01-11 15:13:52 +00:00
} else if (typeof moduleOpts === 'object') {
// Type 3: Pure object
({ src, options, handler } = moduleOpts)
2018-01-11 13:28:45 +00:00
}
2017-07-03 11:11:40 +00:00
// Define handler if src is a function
if (typeof src === 'function') {
handler = src
}
// Prevent adding buildModules-listed entries in production
if (this.options.buildModules.includes(handler) && this.options._start) {
return
}
2018-01-11 13:28:45 +00:00
// Resolve handler
if (!handler) {
try {
handler = this.nuxt.resolver.requireModule(src, { useESM: true })
} catch (error) {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error
}
let message = 'Module `{name}` not found.'
if (this.options.buildModules.includes(src)) {
message += ' Please ensure `{name}` is in `devDependencies` and installed. HINT: During build step, for npm/yarn, `NODE_ENV=production` or `--production` should NOT be used.'.replace('{name}', src)
} else if (this.options.modules.includes(src)) {
message += ' Please ensure `{name}` is in `dependencies` and installed.'
}
message = message.replace(/{name}/g, src)
if (this.options._cli) {
throw new Error(message)
} else {
// TODO: Remove in next major version
2020-04-14 09:26:40 +00:00
message += ' Silently ignoring module as programmatic usage detected.'
consola.warn(message)
return
}
}
2017-05-11 10:59:08 +00:00
}
2017-06-13 22:09:03 +00:00
2018-01-11 13:28:45 +00:00
// Validate handler
if (typeof handler !== 'function') {
throw new TypeError('Module should export a function: ' + src)
2017-05-11 10:59:08 +00:00
}
2017-07-03 11:11:40 +00:00
2020-05-18 11:58:48 +00:00
// Ensure module is required once
const key = (handler.meta && handler.meta.name) || src
if (typeof key === 'string') {
2020-05-18 11:58:48 +00:00
if (this.requiredModules[key]) {
2017-06-05 08:52:02 +00:00
return
}
2018-01-11 13:28:45 +00:00
this.requiredModules[key] = { src, options, handler }
2017-06-05 08:52:02 +00:00
}
2017-07-03 11:11:40 +00:00
// Default module options to empty object
if (options === undefined) {
options = {}
}
const result = await handler.call(this, options)
return result
2017-05-11 10:04:15 +00:00
}
}