config.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. /*!
  2. * @nuxt/config v2.15.8 (c) 2016-2021
  3. * Released under the MIT License
  4. * Repository: https://github.com/nuxt/nuxt.js
  5. * Website: https://nuxtjs.org
  6. */
  7. 'use strict';
  8. Object.defineProperty(exports, '__esModule', { value: true });
  9. const lodash = require('lodash');
  10. const env = require('std-env');
  11. const utils = require('@nuxt/utils');
  12. const path = require('path');
  13. const fs = require('fs');
  14. const defu = require('defu');
  15. const consola = require('consola');
  16. const destr = require('destr');
  17. const ufo = require('ufo');
  18. const dotenv = require('dotenv');
  19. const rc = require('rc9');
  20. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  21. function _interopNamespace(e) {
  22. if (e && e.__esModule) return e;
  23. var n = Object.create(null);
  24. if (e) {
  25. Object.keys(e).forEach(function (k) {
  26. if (k !== 'default') {
  27. var d = Object.getOwnPropertyDescriptor(e, k);
  28. Object.defineProperty(n, k, d.get ? d : {
  29. enumerable: true,
  30. get: function () {
  31. return e[k];
  32. }
  33. });
  34. }
  35. });
  36. }
  37. n['default'] = e;
  38. return Object.freeze(n);
  39. }
  40. const env__default = /*#__PURE__*/_interopDefaultLegacy(env);
  41. const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  42. const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
  43. const defu__default = /*#__PURE__*/_interopDefaultLegacy(defu);
  44. const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
  45. const destr__default = /*#__PURE__*/_interopDefaultLegacy(destr);
  46. const dotenv__default = /*#__PURE__*/_interopDefaultLegacy(dotenv);
  47. const rc__namespace = /*#__PURE__*/_interopNamespace(rc);
  48. const _app = () => ({
  49. vue: {
  50. config: {
  51. silent: undefined, // = !dev
  52. performance: undefined // = dev
  53. }
  54. },
  55. vueMeta: null,
  56. head: {
  57. meta: [],
  58. link: [],
  59. style: [],
  60. script: []
  61. },
  62. fetch: {
  63. server: true,
  64. client: true
  65. },
  66. plugins: [],
  67. extendPlugins: null,
  68. css: [],
  69. layouts: {},
  70. ErrorPage: null,
  71. loading: {
  72. color: 'black',
  73. failedColor: 'red',
  74. height: '2px',
  75. throttle: 200,
  76. duration: 5000,
  77. continuous: false,
  78. rtl: false,
  79. css: true
  80. },
  81. loadingIndicator: 'default',
  82. pageTransition: {
  83. name: 'page',
  84. mode: 'out-in',
  85. appear: false,
  86. appearClass: 'appear',
  87. appearActiveClass: 'appear-active',
  88. appearToClass: 'appear-to'
  89. },
  90. layoutTransition: {
  91. name: 'layout',
  92. mode: 'out-in'
  93. },
  94. features: {
  95. store: true,
  96. layouts: true,
  97. meta: true,
  98. middleware: true,
  99. transitions: true,
  100. deprecations: true,
  101. validate: true,
  102. asyncData: true,
  103. fetch: true,
  104. clientOnline: true,
  105. clientPrefetch: true,
  106. componentAliases: true,
  107. componentClientOnly: true
  108. }
  109. });
  110. const _common = () => ({
  111. // Env
  112. dev: Boolean(env__default['default'].dev),
  113. test: Boolean(env__default['default'].test),
  114. debug: undefined, // = dev
  115. env: {},
  116. createRequire: undefined,
  117. // Target
  118. target: utils.TARGETS.server,
  119. // Rendering
  120. ssr: true,
  121. // Mode (deprecated)
  122. mode: undefined,
  123. // Modern
  124. modern: undefined,
  125. // Modules
  126. modules: [],
  127. buildModules: [],
  128. _modules: [],
  129. globalName: undefined,
  130. globals: {
  131. id: globalName => `__${globalName}`,
  132. nuxt: globalName => `$${globalName}`,
  133. context: globalName => `__${globalName.toUpperCase()}__`,
  134. pluginPrefix: globalName => globalName,
  135. readyCallback: globalName => `on${lodash.capitalize(globalName)}Ready`,
  136. loadedCallback: globalName => `_on${lodash.capitalize(globalName)}Loaded`
  137. },
  138. // Server
  139. serverMiddleware: [],
  140. // Dirs and extensions
  141. _nuxtConfigFile: undefined,
  142. srcDir: undefined,
  143. buildDir: '.nuxt',
  144. modulesDir: [
  145. 'node_modules'
  146. ],
  147. dir: {
  148. assets: 'assets',
  149. app: 'app',
  150. layouts: 'layouts',
  151. middleware: 'middleware',
  152. pages: 'pages',
  153. static: 'static',
  154. store: 'store'
  155. },
  156. extensions: [],
  157. styleExtensions: ['css', 'pcss', 'postcss', 'styl', 'stylus', 'scss', 'sass', 'less'],
  158. alias: {},
  159. // Ignores
  160. ignoreOptions: undefined,
  161. ignorePrefix: '-',
  162. ignore: [
  163. '**/*.test.*',
  164. '**/*.spec.*'
  165. ],
  166. // Watch
  167. watch: [],
  168. watchers: {
  169. rewatchOnRawEvents: undefined,
  170. webpack: {
  171. aggregateTimeout: 1000
  172. },
  173. chokidar: {
  174. ignoreInitial: true
  175. }
  176. },
  177. // Editor
  178. editor: undefined,
  179. // Hooks
  180. hooks: null,
  181. // runtimeConfig
  182. privateRuntimeConfig: {},
  183. publicRuntimeConfig: {}
  184. });
  185. const build = () => ({
  186. quiet: Boolean(env__default['default'].ci || env__default['default'].test),
  187. analyze: false,
  188. profile: process.argv.includes('--profile'),
  189. extractCSS: false,
  190. cssSourceMap: undefined,
  191. ssr: undefined,
  192. parallel: false,
  193. cache: false,
  194. standalone: false,
  195. publicPath: '/_nuxt/',
  196. serverURLPolyfill: 'url',
  197. filenames: {
  198. // { isDev, isClient, isServer }
  199. app: ({ isDev, isModern }) => isDev ? `[name]${isModern ? '.modern' : ''}.js` : `[contenthash:7]${isModern ? '.modern' : ''}.js`,
  200. chunk: ({ isDev, isModern }) => isDev ? `[name]${isModern ? '.modern' : ''}.js` : `[contenthash:7]${isModern ? '.modern' : ''}.js`,
  201. css: ({ isDev }) => isDev ? '[name].css' : 'css/[contenthash:7].css',
  202. img: ({ isDev }) => isDev ? '[path][name].[ext]' : 'img/[name].[contenthash:7].[ext]',
  203. font: ({ isDev }) => isDev ? '[path][name].[ext]' : 'fonts/[name].[contenthash:7].[ext]',
  204. video: ({ isDev }) => isDev ? '[path][name].[ext]' : 'videos/[name].[contenthash:7].[ext]'
  205. },
  206. loaders: {
  207. file: { esModule: false },
  208. fontUrl: { esModule: false, limit: 1000 },
  209. imgUrl: { esModule: false, limit: 1000 },
  210. pugPlain: {},
  211. vue: {
  212. transformAssetUrls: {
  213. video: 'src',
  214. source: 'src',
  215. object: 'src',
  216. embed: 'src'
  217. }
  218. },
  219. css: {
  220. esModule: false,
  221. modules: {
  222. compileType: 'icss'
  223. }
  224. },
  225. cssModules: {
  226. esModule: false,
  227. modules: {
  228. localIdentName: '[local]_[hash:base64:5]'
  229. }
  230. },
  231. less: {},
  232. sass: {
  233. sassOptions: {
  234. indentedSyntax: true
  235. }
  236. },
  237. scss: {},
  238. stylus: {},
  239. vueStyle: {}
  240. },
  241. styleResources: {},
  242. plugins: [],
  243. terser: {},
  244. hardSource: false,
  245. aggressiveCodeRemoval: false,
  246. optimizeCSS: undefined,
  247. optimization: {
  248. runtimeChunk: 'single',
  249. minimize: undefined,
  250. minimizer: undefined,
  251. splitChunks: {
  252. chunks: 'all',
  253. automaticNameDelimiter: '/',
  254. cacheGroups: {}
  255. }
  256. },
  257. splitChunks: {
  258. layouts: false,
  259. pages: true,
  260. commons: true
  261. },
  262. corejs: 'auto',
  263. babel: {
  264. configFile: false,
  265. babelrc: false,
  266. cacheDirectory: undefined
  267. },
  268. transpile: [], // Name of NPM packages to be transpiled
  269. postcss: {
  270. preset: {
  271. // https://cssdb.org/#staging-process
  272. stage: 2
  273. }
  274. },
  275. html: {
  276. minify: {
  277. collapseBooleanAttributes: true,
  278. decodeEntities: true,
  279. minifyCSS: true,
  280. minifyJS: true,
  281. processConditionalComments: true,
  282. removeEmptyAttributes: true,
  283. removeRedundantAttributes: true,
  284. trimCustomFragments: true,
  285. useShortDoctype: true
  286. }
  287. },
  288. template: undefined,
  289. templates: [],
  290. watch: [],
  291. devMiddleware: {
  292. // stats will be printed by webapckbar StateReporter
  293. stats: 'none'
  294. },
  295. hotMiddleware: {},
  296. stats: {
  297. excludeAssets: [
  298. /.map$/,
  299. /index\..+\.html$/,
  300. /vue-ssr-(client|modern)-manifest.json/
  301. ]
  302. },
  303. friendlyErrors: true,
  304. additionalExtensions: [],
  305. warningIgnoreFilters: [],
  306. followSymlinks: false,
  307. loadingScreen: {},
  308. indicator: {
  309. position: 'bottom-right',
  310. backgroundColor: '#2E495E',
  311. color: '#00C48D'
  312. }
  313. });
  314. const messages = () => ({
  315. loading: 'Loading...',
  316. error_404: 'This page could not be found',
  317. server_error: 'Server error',
  318. nuxtjs: 'Nuxt',
  319. back_to_home: 'Back to the home page',
  320. server_error_details:
  321. 'An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.',
  322. client_error: 'Error',
  323. client_error_details:
  324. 'An error occurred while rendering the page. Check developer tools console for details.'
  325. });
  326. const modes = () => ({
  327. [utils.MODES.universal]: {
  328. build: {
  329. ssr: true
  330. },
  331. render: {
  332. ssr: true
  333. }
  334. },
  335. [utils.MODES.spa]: {
  336. build: {
  337. ssr: false
  338. },
  339. render: {
  340. ssr: false
  341. }
  342. }
  343. });
  344. // TODO: Refactor @nuxt/server related options into `server.js`
  345. const render = () => ({
  346. bundleRenderer: {
  347. shouldPrefetch: () => false,
  348. shouldPreload: (fileWithoutQuery, asType) => ['script', 'style'].includes(asType),
  349. runInNewContext: undefined
  350. },
  351. crossorigin: undefined,
  352. resourceHints: true,
  353. ssr: undefined,
  354. ssrLog: undefined,
  355. http2: {
  356. push: false,
  357. shouldPush: null,
  358. pushAssets: null
  359. },
  360. static: {
  361. prefix: true
  362. },
  363. compressor: {
  364. threshold: 0
  365. },
  366. etag: {
  367. weak: false
  368. },
  369. csp: false,
  370. dist: {
  371. // Don't serve index.html template
  372. index: false,
  373. // 1 year in production
  374. maxAge: '1y'
  375. },
  376. // https://github.com/nuxt/serve-placeholder
  377. fallback: {
  378. dist: {},
  379. static: {
  380. skipUnknown: true,
  381. handlers: {
  382. '.htm': false,
  383. '.html': false
  384. }
  385. }
  386. }
  387. });
  388. const router = () => ({
  389. mode: 'history',
  390. base: '/',
  391. routes: [],
  392. routeNameSplitter: '-',
  393. middleware: [],
  394. linkActiveClass: 'nuxt-link-active',
  395. linkExactActiveClass: 'nuxt-link-exact-active',
  396. linkPrefetchedClass: false,
  397. extendRoutes: null,
  398. scrollBehavior: null,
  399. parseQuery: false,
  400. stringifyQuery: false,
  401. fallback: false,
  402. prefetchLinks: true,
  403. prefetchPayloads: true,
  404. trailingSlash: undefined
  405. });
  406. const server = ({ env = {} } = {}) => ({
  407. https: false,
  408. port: env.NUXT_PORT ||
  409. env.PORT ||
  410. env.npm_package_config_nuxt_port ||
  411. 3000,
  412. host: env.NUXT_HOST ||
  413. env.HOST ||
  414. env.npm_package_config_nuxt_host ||
  415. 'localhost',
  416. socket: env.UNIX_SOCKET ||
  417. env.npm_package_config_unix_socket,
  418. timing: false
  419. });
  420. const cli = () => ({
  421. badgeMessages: [],
  422. bannerColor: 'green'
  423. });
  424. const generate = () => ({
  425. dir: 'dist',
  426. routes: [],
  427. exclude: [],
  428. concurrency: 500,
  429. interval: 0,
  430. subFolders: true,
  431. fallback: '200.html',
  432. crawler: true,
  433. manifest: true,
  434. cache: {
  435. ignore: [],
  436. globbyOptions: {
  437. gitignore: true
  438. }
  439. },
  440. staticAssets: {
  441. base: undefined, // Default: "/_nuxt/static:
  442. versionBase: undefined, // Default: "_nuxt/static/{version}""
  443. dir: 'static',
  444. version: undefined // Default: "{timeStampSec}"
  445. }
  446. });
  447. const defaultNuxtConfigFile = 'nuxt.config';
  448. function getDefaultNuxtConfig (options = {}) {
  449. if (!options.env) {
  450. options.env = process.env;
  451. }
  452. return {
  453. ..._app(),
  454. ..._common(),
  455. build: build(),
  456. messages: messages(),
  457. modes: modes(),
  458. render: render(),
  459. router: router(),
  460. server: server(options),
  461. cli: cli(),
  462. generate: generate()
  463. }
  464. }
  465. function getNuxtConfig (_options) {
  466. // Prevent duplicate calls
  467. if (_options.__normalized__) {
  468. return _options
  469. }
  470. // Clone options to prevent unwanted side-effects
  471. const options = Object.assign({}, _options);
  472. options.__normalized__ = true;
  473. // Normalize options
  474. if (options.loading === true) {
  475. delete options.loading;
  476. }
  477. if (
  478. options.router &&
  479. options.router.middleware &&
  480. !Array.isArray(options.router.middleware)
  481. ) {
  482. options.router.middleware = [options.router.middleware];
  483. }
  484. if (options.router && typeof options.router.base === 'string') {
  485. options._routerBaseSpecified = true;
  486. }
  487. // TODO: Remove for Nuxt 3
  488. // router.scrollBehavior -> app/router.scrollBehavior.js
  489. if (options.router && typeof options.router.scrollBehavior !== 'undefined') {
  490. consola__default['default'].warn('`router.scrollBehavior` property is deprecated in favor of using `~/app/router.scrollBehavior.js` file, learn more: https://nuxtjs.org/api/configuration-router#scrollbehavior');
  491. }
  492. // TODO: Remove for Nuxt 3
  493. // transition -> pageTransition
  494. if (typeof options.transition !== 'undefined') {
  495. consola__default['default'].warn('`transition` property is deprecated in favor of `pageTransition` and will be removed in Nuxt 3');
  496. options.pageTransition = options.transition;
  497. delete options.transition;
  498. }
  499. if (typeof options.pageTransition === 'string') {
  500. options.pageTransition = { name: options.pageTransition };
  501. }
  502. if (typeof options.layoutTransition === 'string') {
  503. options.layoutTransition = { name: options.layoutTransition };
  504. }
  505. if (typeof options.extensions === 'string') {
  506. options.extensions = [options.extensions];
  507. }
  508. options.globalName = (utils.isNonEmptyString(options.globalName) && /^[a-zA-Z]+$/.test(options.globalName))
  509. ? options.globalName.toLowerCase()
  510. // use `` for preventing replacing to nuxt-edge
  511. : `nuxt`;
  512. // Resolve rootDir
  513. options.rootDir = utils.isNonEmptyString(options.rootDir) ? path__default['default'].resolve(options.rootDir) : process.cwd();
  514. // Apply defaults by ${buildDir}/dist/build.config.js
  515. // TODO: Unsafe operation.
  516. // const buildDir = options.buildDir || defaults.buildDir
  517. // const buildConfig = resolve(options.rootDir, buildDir, 'build.config.js')
  518. // if (existsSync(buildConfig)) {
  519. // defaultsDeep(options, require(buildConfig))
  520. // }
  521. // Apply defaults
  522. const nuxtConfig = getDefaultNuxtConfig();
  523. nuxtConfig.build._publicPath = nuxtConfig.build.publicPath;
  524. // Fall back to default if publicPath is falsy
  525. if (options.build && !options.build.publicPath) {
  526. options.build.publicPath = undefined;
  527. }
  528. lodash.defaultsDeep(options, nuxtConfig);
  529. // Target
  530. options.target = options.target || 'server';
  531. if (!Object.values(utils.TARGETS).includes(options.target)) {
  532. consola__default['default'].warn(`Unknown target: ${options.target}. Falling back to server`);
  533. options.target = 'server';
  534. }
  535. // Deprecate Mode
  536. if (options.mode) {
  537. if ((options.mode === utils.MODES.universal && options.ssr) || (options.mode === utils.MODES.spa && !options.ssr)) {
  538. consola__default['default'].warn('`mode` option is deprecated. You can safely remove it from `nuxt.config`');
  539. } else {
  540. consola__default['default'].warn('`mode` option is deprecated. Please use `ssr: true` for universal mode or `ssr: false` for spa mode and remove `mode` from `nuxt.config`');
  541. }
  542. } else {
  543. // For backward compat we need default value
  544. options.mode = utils.MODES.universal;
  545. }
  546. // SSR root option
  547. if (options.ssr === false) {
  548. options.mode = utils.MODES.spa;
  549. }
  550. // Apply mode preset
  551. const modePreset = options.modes[options.mode || utils.MODES.universal];
  552. if (!modePreset) {
  553. consola__default['default'].warn(`Unknown mode: ${options.mode}. Falling back to ${utils.MODES.universal}`);
  554. }
  555. lodash.defaultsDeep(options, modePreset || options.modes[utils.MODES.universal]);
  556. // Sanitize router.base
  557. options.router.base = ufo.withTrailingSlash(ufo.normalizeURL(options.router.base));
  558. // Legacy support for export
  559. if (options.export) {
  560. consola__default['default'].warn('export option is deprecated and will be removed in a future version! Please switch to generate');
  561. options.generate = defu__default['default'](options.export, options.generate);
  562. }
  563. exports.export = options.generate;
  564. // Check srcDir and generate.dir existence
  565. const hasSrcDir = utils.isNonEmptyString(options.srcDir);
  566. const hasGenerateDir = utils.isNonEmptyString(options.generate.dir);
  567. // Resolve srcDir
  568. options.srcDir = hasSrcDir
  569. ? path__default['default'].resolve(options.rootDir, options.srcDir)
  570. : options.rootDir;
  571. // Resolve buildDir
  572. options.buildDir = path__default['default'].resolve(options.rootDir, options.buildDir);
  573. // Aliases
  574. const { rootDir, srcDir, dir: { assets: assetsDir, static: staticDir } } = options;
  575. options.alias = {
  576. '~~': rootDir,
  577. '@@': rootDir,
  578. '~': srcDir,
  579. '@': srcDir,
  580. [assetsDir]: path__default['default'].join(srcDir, assetsDir),
  581. [staticDir]: path__default['default'].join(srcDir, staticDir),
  582. ...options.alias
  583. };
  584. // Default value for _nuxtConfigFile
  585. if (!options._nuxtConfigFile) {
  586. options._nuxtConfigFile = path__default['default'].resolve(options.rootDir, `${defaultNuxtConfigFile}.js`);
  587. }
  588. if (!options._nuxtConfigFiles) {
  589. options._nuxtConfigFiles = [
  590. options._nuxtConfigFile
  591. ];
  592. }
  593. // Watch for config file changes
  594. options.watch.push(...options._nuxtConfigFiles);
  595. // Protect rootDir against buildDir
  596. utils.guardDir(options, 'rootDir', 'buildDir');
  597. if (hasGenerateDir) {
  598. // Resolve generate.dir
  599. options.generate.dir = path__default['default'].resolve(options.rootDir, options.generate.dir);
  600. // Protect rootDir against buildDir
  601. utils.guardDir(options, 'rootDir', 'generate.dir');
  602. }
  603. if (hasSrcDir) {
  604. // Protect srcDir against buildDir
  605. utils.guardDir(options, 'srcDir', 'buildDir');
  606. if (hasGenerateDir) {
  607. // Protect srcDir against generate.dir
  608. utils.guardDir(options, 'srcDir', 'generate.dir');
  609. }
  610. }
  611. // Populate modulesDir
  612. options.modulesDir = lodash.uniq(
  613. utils.getMainModule().paths.concat(
  614. [].concat(options.modulesDir).map(dir => path__default['default'].resolve(options.rootDir, dir))
  615. )
  616. );
  617. const mandatoryExtensions = ['js', 'mjs'];
  618. options.extensions = mandatoryExtensions
  619. .filter(ext => !options.extensions.includes(ext))
  620. .concat(options.extensions);
  621. // If app.html is defined, set the template path to the user template
  622. if (options.appTemplatePath === undefined) {
  623. options.appTemplatePath = path__default['default'].resolve(options.buildDir, 'views/app.template.html');
  624. if (fs__default['default'].existsSync(path__default['default'].join(options.srcDir, 'app.html'))) {
  625. options.appTemplatePath = path__default['default'].join(options.srcDir, 'app.html');
  626. }
  627. } else {
  628. options.appTemplatePath = path__default['default'].resolve(options.srcDir, options.appTemplatePath);
  629. }
  630. options.build.publicPath = options.build.publicPath.replace(/([^/])$/, '$1/');
  631. options.build._publicPath = options.build._publicPath.replace(/([^/])$/, '$1/');
  632. // Ignore publicPath on dev
  633. if (options.dev && utils.isUrl(options.build.publicPath)) {
  634. options.build.publicPath = options.build._publicPath;
  635. }
  636. // If store defined, update store options to true unless explicitly disabled
  637. if (
  638. options.store !== false &&
  639. fs__default['default'].existsSync(path__default['default'].join(options.srcDir, options.dir.store)) &&
  640. fs__default['default'].readdirSync(path__default['default'].join(options.srcDir, options.dir.store))
  641. .find(filename => filename !== 'README.md' && filename[0] !== '.')
  642. ) {
  643. options.store = true;
  644. }
  645. // SPA loadingIndicator
  646. if (options.loadingIndicator) {
  647. // Normalize loadingIndicator
  648. if (!utils.isPureObject(options.loadingIndicator)) {
  649. options.loadingIndicator = { name: options.loadingIndicator };
  650. }
  651. // Apply defaults
  652. options.loadingIndicator = Object.assign(
  653. {
  654. name: 'default',
  655. color: (options.loading && options.loading.color) || '#D3D3D3',
  656. color2: '#F5F5F5',
  657. background: (options.manifest && options.manifest.theme_color) || 'white',
  658. dev: options.dev,
  659. loading: options.messages.loading
  660. },
  661. options.loadingIndicator
  662. );
  663. }
  664. // Debug errors
  665. if (options.debug === undefined) {
  666. options.debug = options.dev;
  667. }
  668. // Validate that etag.hash is a function, if not unset it
  669. if (options.render.etag) {
  670. const { hash } = options.render.etag;
  671. if (hash) {
  672. const isFn = typeof hash === 'function';
  673. if (!isFn) {
  674. options.render.etag.hash = undefined;
  675. if (options.dev) {
  676. consola__default['default'].warn(`render.etag.hash should be a function, received ${typeof hash} instead`);
  677. }
  678. }
  679. }
  680. }
  681. // Apply default hash to CSP option
  682. if (options.render.csp) {
  683. options.render.csp = defu__default['default'](options.render.csp, {
  684. hashAlgorithm: 'sha256',
  685. allowedSources: undefined,
  686. policies: undefined,
  687. addMeta: Boolean(options.target === utils.TARGETS.static),
  688. unsafeInlineCompatibility: false,
  689. reportOnly: options.debug
  690. });
  691. // TODO: Remove this if statement in Nuxt 3, we will stop supporting this typo (more on: https://github.com/nuxt/nuxt.js/pull/6583)
  692. if (options.render.csp.unsafeInlineCompatiblity) {
  693. consola__default['default'].warn('Using `unsafeInlineCompatiblity` is deprecated and will be removed in Nuxt 3. Use `unsafeInlineCompatibility` instead.');
  694. options.render.csp.unsafeInlineCompatibility = options.render.csp.unsafeInlineCompatiblity;
  695. delete options.render.csp.unsafeInlineCompatiblity;
  696. }
  697. }
  698. // cssSourceMap
  699. if (options.build.cssSourceMap === undefined) {
  700. options.build.cssSourceMap = options.dev;
  701. }
  702. const babelConfig = options.build.babel;
  703. // babel cacheDirectory
  704. if (babelConfig.cacheDirectory === undefined) {
  705. babelConfig.cacheDirectory = options.dev;
  706. }
  707. // TODO: remove this warn in Nuxt 3
  708. if (Array.isArray(babelConfig.presets)) {
  709. const warnPreset = (presetName) => {
  710. const oldPreset = '@nuxtjs/babel-preset-app';
  711. const newPreset = '@nuxt/babel-preset-app';
  712. if (presetName.includes(oldPreset)) {
  713. presetName = presetName.replace(oldPreset, newPreset);
  714. consola__default['default'].warn('@nuxtjs/babel-preset-app has been deprecated, please use @nuxt/babel-preset-app.');
  715. }
  716. return presetName
  717. };
  718. babelConfig.presets = babelConfig.presets.map((preset) => {
  719. const hasOptions = Array.isArray(preset);
  720. if (hasOptions) {
  721. preset[0] = warnPreset(preset[0]);
  722. } else if (typeof preset === 'string') {
  723. preset = warnPreset(preset);
  724. }
  725. return preset
  726. });
  727. }
  728. // Vue config
  729. const vueConfig = options.vue.config;
  730. if (vueConfig.silent === undefined) {
  731. vueConfig.silent = !options.dev;
  732. }
  733. if (vueConfig.performance === undefined) {
  734. vueConfig.performance = options.dev;
  735. }
  736. // merge custom env with variables
  737. const eligibleEnvVariables = lodash.pick(process.env, Object.keys(process.env).filter(k => k.startsWith('NUXT_ENV_')));
  738. Object.assign(options.env, eligibleEnvVariables);
  739. // Normalize ignore
  740. options.ignore = options.ignore ? [].concat(options.ignore) : [];
  741. // Append ignorePrefix glob to ignore
  742. if (typeof options.ignorePrefix === 'string') {
  743. options.ignore.push(`**/${options.ignorePrefix}*.*`);
  744. }
  745. // Compression middleware legacy
  746. if (options.render.gzip) {
  747. consola__default['default'].warn('render.gzip is deprecated and will be removed in a future version! Please switch to render.compressor');
  748. options.render.compressor = options.render.gzip;
  749. delete options.render.gzip;
  750. }
  751. // If no server-side rendering, add appear true transition
  752. if (options.render.ssr === false && options.pageTransition) {
  753. options.pageTransition.appear = true;
  754. }
  755. options.render.ssrLog = options.dev
  756. ? options.render.ssrLog === undefined || options.render.ssrLog
  757. : false;
  758. // We assume the SPA fallback path is 404.html (for GitHub Pages, Surge, etc.)
  759. if (options.generate.fallback === true) {
  760. options.generate.fallback = '404.html';
  761. }
  762. if (options.build.stats === 'none' || options.build.quiet === true) {
  763. options.build.stats = false;
  764. }
  765. // Vendor backward compatibility with nuxt 1.x
  766. if (typeof options.build.vendor !== 'undefined') {
  767. delete options.build.vendor;
  768. consola__default['default'].warn('vendor has been deprecated due to webpack4 optimization');
  769. }
  770. // Disable CSS extraction due to incompatibility with thread-loader
  771. if (options.build.extractCSS && options.build.parallel) {
  772. options.build.parallel = false;
  773. consola__default['default'].warn('extractCSS cannot work with parallel build due to limited work pool in thread-loader');
  774. }
  775. // build.extractCSS.allChunks has no effect
  776. if (typeof options.build.extractCSS.allChunks !== 'undefined') {
  777. consola__default['default'].warn('build.extractCSS.allChunks has no effect from v2.0.0. Please use build.optimization.splitChunks settings instead.');
  778. }
  779. // devModules has been renamed to buildModules
  780. if (typeof options.devModules !== 'undefined') {
  781. consola__default['default'].warn('`devModules` has been renamed to `buildModules` and will be removed in Nuxt 3.');
  782. options.buildModules.push(...options.devModules);
  783. delete options.devModules;
  784. }
  785. // Enable minimize for production builds
  786. if (options.build.optimization.minimize === undefined) {
  787. options.build.optimization.minimize = !options.dev;
  788. }
  789. // Enable optimizeCSS only when extractCSS is enabled
  790. if (options.build.optimizeCSS === undefined) {
  791. options.build.optimizeCSS = options.build.extractCSS ? {} : false;
  792. }
  793. const { loaders } = options.build;
  794. const vueLoader = loaders.vue;
  795. if (vueLoader.productionMode === undefined) {
  796. vueLoader.productionMode = !options.dev;
  797. }
  798. const styleLoaders = [
  799. 'css', 'cssModules', 'less',
  800. 'sass', 'scss', 'stylus', 'vueStyle'
  801. ];
  802. for (const name of styleLoaders) {
  803. const loader = loaders[name];
  804. if (loader && loader.sourceMap === undefined) {
  805. loader.sourceMap = Boolean(options.build.cssSourceMap);
  806. }
  807. }
  808. options.build.transpile = [].concat(options.build.transpile || []);
  809. if (options.build.quiet === true) {
  810. consola__default['default'].level = 0;
  811. }
  812. // Use runInNewContext for dev mode by default
  813. const { bundleRenderer } = options.render;
  814. if (typeof bundleRenderer.runInNewContext === 'undefined') {
  815. bundleRenderer.runInNewContext = options.dev;
  816. }
  817. // TODO: Remove this if statement in Nuxt 3
  818. if (options.build.crossorigin) {
  819. consola__default['default'].warn('Using `build.crossorigin` is deprecated and will be removed in Nuxt 3. Please use `render.crossorigin` instead.');
  820. options.render.crossorigin = options.build.crossorigin;
  821. delete options.build.crossorigin;
  822. }
  823. const { timing } = options.server;
  824. if (timing) {
  825. options.server.timing = { total: true, ...timing };
  826. }
  827. if (utils.isPureObject(options.serverMiddleware)) {
  828. options.serverMiddleware = Object.entries(options.serverMiddleware)
  829. .map(([path, handler]) => ({ path, handler }));
  830. }
  831. // App config (internal for nuxt2 at this stage)
  832. const useCDN = utils.isUrl(options.build.publicPath) && !options.dev;
  833. const isRelativePublicPath = ufo.isRelative(options.build.publicPath);
  834. options.app = defu__default['default'](options.app, {
  835. basePath: options.router.base,
  836. assetsPath: isRelativePublicPath ? options.build.publicPath : useCDN ? '/' : ufo.joinURL(options.router.base, options.build.publicPath),
  837. cdnURL: useCDN ? options.build.publicPath : null
  838. });
  839. // Expose app config to $config._app
  840. options.publicRuntimeConfig = options.publicRuntimeConfig || {};
  841. options.publicRuntimeConfig._app = options.app;
  842. // Generate staticAssets
  843. const { staticAssets } = options.generate;
  844. if (!staticAssets.version) {
  845. staticAssets.version = String(Math.round(Date.now() / 1000));
  846. }
  847. if (!staticAssets.base) {
  848. staticAssets.base = ufo.joinURL(options.app.assetsPath, staticAssets.dir);
  849. }
  850. if (!staticAssets.versionBase) {
  851. staticAssets.versionBase = ufo.joinURL(staticAssets.base, staticAssets.version);
  852. }
  853. // createRequire
  854. const isJest = typeof jest !== 'undefined';
  855. const defaultCreateRequire = isJest ? 'native' : 'jiti';
  856. options.createRequire = process.env.NUXT_CREATE_REQUIRE || options.createRequire || defaultCreateRequire;
  857. if (options.createRequire === 'native' || options.createRequire === 'jiti') {
  858. const useJiti = options.createRequire === 'jiti';
  859. options.createRequire = p => utils.createRequire(typeof p === 'string' ? p : p.filename, useJiti);
  860. } else if (typeof options.createRequire !== 'function') {
  861. throw new TypeError(
  862. `Unsupported createRequire value ${options.createRequire}! Possible values: "native", "jiti", <Function>`
  863. )
  864. }
  865. // Indicator
  866. // Change boolean true to default nuxt value
  867. if (options.build.indicator === true) {
  868. options.build.indicator = nuxtConfig.build.indicator;
  869. }
  870. // ----- Builtin modules -----
  871. // Loading screen
  872. // Force disable for production and programmatic users
  873. if (!options.dev || !options._cli || !utils.getPKG('@nuxt/loading-screen')) {
  874. options.build.loadingScreen = false;
  875. }
  876. if (options.build.loadingScreen) {
  877. options._modules.push(['@nuxt/loading-screen', options.build.loadingScreen]);
  878. } else {
  879. // When loadingScreen is disabled we should also disable build indicator
  880. options.build.indicator = false;
  881. }
  882. // Components Module
  883. if (!options._start && utils.getPKG('@nuxt/components')) {
  884. options._modules.push('@nuxt/components');
  885. }
  886. // Nuxt Telemetry
  887. if (
  888. options.telemetry !== false &&
  889. !options.test &&
  890. !destr__default['default'](process.env.NUXT_TELEMETRY_DISABLED) &&
  891. utils.getPKG('@nuxt/telemetry')
  892. ) {
  893. options._modules.push('@nuxt/telemetry');
  894. }
  895. return options
  896. }
  897. async function loadNuxtConfig ({
  898. rootDir = '.',
  899. envConfig = {},
  900. configFile = defaultNuxtConfigFile,
  901. configContext = {},
  902. configOverrides = {}
  903. } = {}) {
  904. rootDir = path__default['default'].resolve(rootDir);
  905. const _require = utils.createRequire(rootDir, true);
  906. let options = {};
  907. try {
  908. configFile = _require.resolve(path__default['default'].resolve(rootDir, configFile));
  909. } catch (e) {
  910. if (e.code !== 'MODULE_NOT_FOUND') {
  911. throw (e)
  912. } else if (configFile !== defaultNuxtConfigFile) {
  913. consola__default['default'].fatal('Config file not found: ' + configFile);
  914. }
  915. // Skip configFile if cannot resolve
  916. configFile = undefined;
  917. }
  918. // Load env
  919. envConfig = {
  920. dotenv: '.env',
  921. env: process.env,
  922. expand: true,
  923. ...envConfig
  924. };
  925. const env = loadEnv(envConfig, rootDir);
  926. // Fill process.env so it is accessible in nuxt.config
  927. for (const key in env) {
  928. if (!key.startsWith('_') && envConfig.env[key] === undefined) {
  929. envConfig.env[key] = env[key];
  930. }
  931. }
  932. if (configFile) {
  933. // Clear cache
  934. utils.clearRequireCache(configFile);
  935. options = _require(configFile) || {};
  936. if (options.default) {
  937. options = options.default;
  938. }
  939. if (typeof options === 'function') {
  940. try {
  941. options = await options(configContext);
  942. if (options.default) {
  943. options = options.default;
  944. }
  945. } catch (error) {
  946. consola__default['default'].error(error);
  947. consola__default['default'].fatal('Error while fetching async configuration');
  948. }
  949. }
  950. // Don't mutate options export
  951. options = { ...options };
  952. // Keep _nuxtConfigFile for watching
  953. options._nuxtConfigFile = configFile;
  954. // Keep all related files for watching
  955. options._nuxtConfigFiles = Array.from(utils.scanRequireTree(configFile));
  956. if (!options._nuxtConfigFiles.includes(configFile)) {
  957. options._nuxtConfigFiles.unshift(configFile);
  958. }
  959. }
  960. if (typeof options.rootDir !== 'string') {
  961. options.rootDir = rootDir;
  962. }
  963. // Load Combine configs
  964. // Priority: configOverrides > nuxtConfig > .nuxtrc > .nuxtrc (global)
  965. options = defu__default['default'](
  966. configOverrides,
  967. options,
  968. rc__namespace.read({ name: '.nuxtrc', dir: options.rootDir }),
  969. rc__namespace.readUser('.nuxtrc')
  970. );
  971. // Load env to options._env
  972. options._env = env;
  973. options._envConfig = envConfig;
  974. if (configContext) { configContext.env = env; }
  975. // Expand and interpolate runtimeConfig from _env
  976. if (envConfig.expand) {
  977. for (const c of ['publicRuntimeConfig', 'privateRuntimeConfig']) {
  978. if (options[c]) {
  979. if (typeof options[c] === 'function') {
  980. options[c] = options[c](env);
  981. }
  982. expand(options[c], env, destr__default['default']);
  983. }
  984. }
  985. }
  986. return options
  987. }
  988. function loadEnv (envConfig, rootDir = process.cwd()) {
  989. const env = Object.create(null);
  990. // Read dotenv
  991. if (envConfig.dotenv) {
  992. envConfig.dotenv = path__default['default'].resolve(rootDir, envConfig.dotenv);
  993. if (fs__default['default'].existsSync(envConfig.dotenv)) {
  994. const parsed = dotenv__default['default'].parse(fs__default['default'].readFileSync(envConfig.dotenv, 'utf-8'));
  995. Object.assign(env, parsed);
  996. }
  997. }
  998. // Apply process.env
  999. if (!envConfig.env._applied) {
  1000. Object.assign(env, envConfig.env);
  1001. envConfig.env._applied = true;
  1002. }
  1003. // Interpolate env
  1004. if (envConfig.expand) {
  1005. expand(env);
  1006. }
  1007. return env
  1008. }
  1009. // Based on https://github.com/motdotla/dotenv-expand
  1010. function expand (target, source = {}, parse = v => v) {
  1011. function getValue (key) {
  1012. // Source value 'wins' over target value
  1013. return source[key] !== undefined ? source[key] : target[key]
  1014. }
  1015. function interpolate (value, parents = []) {
  1016. if (typeof value !== 'string') {
  1017. return value
  1018. }
  1019. const matches = value.match(/(.?\${?(?:[a-zA-Z0-9_:]+)?}?)/g) || [];
  1020. return parse(matches.reduce((newValue, match) => {
  1021. const parts = /(.?)\${?([a-zA-Z0-9_:]+)?}?/g.exec(match);
  1022. const prefix = parts[1];
  1023. let value, replacePart;
  1024. if (prefix === '\\') {
  1025. replacePart = parts[0];
  1026. value = replacePart.replace('\\$', '$');
  1027. } else {
  1028. const key = parts[2];
  1029. replacePart = parts[0].substring(prefix.length);
  1030. // Avoid recursion
  1031. if (parents.includes(key)) {
  1032. consola__default['default'].warn(`Please avoid recursive environment variables ( loop: ${parents.join(' > ')} > ${key} )`);
  1033. return ''
  1034. }
  1035. value = getValue(key);
  1036. // Resolve recursive interpolations
  1037. value = interpolate(value, [...parents, key]);
  1038. }
  1039. return value !== undefined ? newValue.replace(replacePart, value) : newValue
  1040. }, value))
  1041. }
  1042. for (const key in target) {
  1043. target[key] = interpolate(getValue(key));
  1044. }
  1045. }
  1046. exports.defaultNuxtConfigFile = defaultNuxtConfigFile;
  1047. exports.getDefaultNuxtConfig = getDefaultNuxtConfig;
  1048. exports.getNuxtConfig = getNuxtConfig;
  1049. exports.loadNuxtConfig = loadNuxtConfig;