feat: rewrite core to esm

This commit is contained in:
Pooya Parsa 2018-03-16 19:42:06 +03:30
parent b0f25cbadf
commit 53e98a958c
124 changed files with 427 additions and 426 deletions

View File

@ -1,6 +1,7 @@
const { Utils } = require('../..') const { Utils } = require('../..')
const { resolve } = require('path') const { resolve } = require('path')
const { existsSync } = require('fs') const { existsSync } = require('fs')
const { requireModule } = require('../../lib/common/module')
const getRootDir = argv => resolve(argv._[0] || '.') const getRootDir = argv => resolve(argv._[0] || '.')
const getNuxtConfigFile = argv => resolve(getRootDir(argv), argv['config-file']) const getNuxtConfigFile = argv => resolve(getRootDir(argv), argv['config-file'])
@ -15,7 +16,7 @@ exports.loadNuxtConfig = argv => {
if (existsSync(nuxtConfigFile)) { if (existsSync(nuxtConfigFile)) {
delete require.cache[nuxtConfigFile] delete require.cache[nuxtConfigFile]
options = require(nuxtConfigFile) options = requireModule(nuxtConfigFile)
} else if (argv['config-file'] !== 'nuxt.config.js') { } else if (argv['config-file'] !== 'nuxt.config.js') {
Utils.fatalError('Could not load config file: ' + argv['config-file']) Utils.fatalError('Could not load config file: ' + argv['config-file'])
} }

View File

@ -3,17 +3,15 @@
const defaultsDeep = require('lodash/defaultsDeep') const defaultsDeep = require('lodash/defaultsDeep')
const debug = require('debug')('nuxt:build') const debug = require('debug')('nuxt:build')
debug.color = 2 // force green color
const parseArgs = require('minimist') const parseArgs = require('minimist')
const chokidar = require('chokidar') const chokidar = require('chokidar')
const { version } = require('../package.json')
const { version } = require('../package.json')
const { Nuxt, Builder, Utils } = require('..') const { Nuxt, Builder, Utils } = require('..')
const {
loadNuxtConfig, const { loadNuxtConfig, getLatestHost, nuxtConfigFile } = require('./common/utils')
getLatestHost,
nuxtConfigFile debug.color = 2 // force green color
} = require('./common/utils')
const argv = parseArgs(process.argv.slice(2), { const argv = parseArgs(process.argv.slice(2), {
alias: { alias: {

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
title: 'Nuxt Blog', title: 'Nuxt Blog',
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
loading: { loading: {
color: '#4FC08D', color: '#4FC08D',
failedColor: '#bf5050', failedColor: '#bf5050',

View File

@ -1,4 +1,4 @@
const express = require('express') import express from 'express'
// Create express router // Create express router
const router = express.Router() const router = express.Router()
@ -30,7 +30,7 @@ router.post('/logout', (req, res) => {
}) })
// Export the server middleware // Export the server middleware
module.exports = { export default {
path: '/api', path: '/api',
handler: router handler: router
} }

View File

@ -1,7 +1,7 @@
const bodyParser = require('body-parser') import bodyParser from 'body-parser'
const session = require('express-session') import session from 'express-session'
module.exports = { export default {
head: { head: {
title: 'Auth Routes', title: 'Auth Routes',
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
modules: [ modules: [
'@nuxtjs/axios', '@nuxtjs/axios',
'@nuxtjs/proxy' '@nuxtjs/proxy'

View File

@ -1,4 +1,4 @@
module.exports = { export default {
render: { render: {
bundleRenderer: { bundleRenderer: {
cache: require('lru-cache')({ cache: require('lru-cache')({

View File

@ -1,4 +1,4 @@
module.exports = function () { export default function () {
// Add .coffee extension for store, middleware and more // Add .coffee extension for store, middleware and more
this.nuxt.options.extensions.push('coffee') this.nuxt.options.extensions.push('coffee')
// Extend build // Extend build

View File

@ -1,4 +1,4 @@
module.exports = { export default {
/* /*
** Headers of the page ** Headers of the page
*/ */

View File

@ -1,4 +1,4 @@
module.exports = { export default {
build: { build: {
filenames: { filenames: {
css: 'styles.[chunkhash].css', // default: common.[chunkhash].css css: 'styles.[chunkhash].css', // default: common.[chunkhash].css

View File

@ -1,3 +1,3 @@
module.exports = { export default {
loading: '~/components/loading.vue' loading: '~/components/loading.vue'
} }

View File

@ -1,2 +1,2 @@
module.exports = { export default {
} }

View File

@ -1 +1 @@
module.exports = {} export default {}

View File

@ -1,5 +1,7 @@
const app = require('express')() import express from 'express'
const { Nuxt, Builder } = require('nuxt') import { Nuxt, Builder } from 'nuxt'
const app = express()
const host = process.env.HOST || '127.0.0.1' const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000 const port = process.env.PORT || 3000

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
titleTemplate: 'Nuxt.js - Dynamic Components', titleTemplate: 'Nuxt.js - Dynamic Components',
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ content: 'width=device-width,initial-scale=1', name: 'viewport' } { content: 'width=device-width,initial-scale=1', name: 'viewport' }

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ charset: 'utf-8' }, { charset: 'utf-8' },

View File

@ -1,4 +1,4 @@
module.exports = { export default {
loading: { color: 'cyan' }, loading: { color: 'cyan' },
router: { router: {
middleware: 'i18n' middleware: 'i18n'

View File

@ -1,4 +1,4 @@
module.exports = { export default {
css: ['~/assets/main.css'], css: ['~/assets/main.css'],
layoutTransition: { layoutTransition: {
name: 'layout', name: 'layout',

View File

@ -1,4 +1,4 @@
module.exports = { export default {
modules: [ modules: [
'@nuxtjs/markdownit' '@nuxtjs/markdownit'
], ],

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
titleTemplate: '%s - Nuxt.js', titleTemplate: '%s - Nuxt.js',
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
router: { router: {
middleware: ['visits', 'user-agent'] middleware: ['visits', 'user-agent']
} }

View File

@ -1,4 +1,4 @@
module.exports = { export default {
loading: false, loading: false,
head: { head: {
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
plugins: [ plugins: [
// ssr: false to only include it on client-side // ssr: false to only include it on client-side
{ src: '~/plugins/vue-notifications.js', ssr: false } { src: '~/plugins/vue-notifications.js', ssr: false }

View File

@ -1,3 +1,3 @@
module.exports = { export default {
css: ['~/assets/main.css'] css: ['~/assets/main.css']
} }

View File

@ -1,3 +1,3 @@
module.exports = { export default {
css: ['~/assets/main.css'] css: ['~/assets/main.css']
} }

View File

@ -1,4 +1,4 @@
module.exports = { export default {
/* /*
** Single Page Application mode ** Single Page Application mode
** Means no SSR ** Means no SSR

View File

@ -1,6 +1,6 @@
const pkg = require('./package') import pkg from './package'
module.exports = { export default {
mode: 'universal', mode: 'universal',
/* /*

View File

@ -1,4 +1,4 @@
module.exports = { export default {
build: { build: {
// You cannot use ~/ or @/ here since it's a Webpack plugin // You cannot use ~/ or @/ here since it's a Webpack plugin
styleResources: { styleResources: {

View File

@ -1,3 +1,3 @@
module.exports = { export default {
css: ['~/assets/css/tailwind.css'] css: ['~/assets/css/tailwind.css']
} }

View File

@ -127,7 +127,7 @@ var colors = {
'pink-lightest': '#ffebef' 'pink-lightest': '#ffebef'
} }
module.exports = { export default {
/* /*
|----------------------------------------------------------------------------- |-----------------------------------------------------------------------------

View File

@ -1,4 +1,4 @@
module.exports = function () { export default function () {
// Add .ts extension for store, middleware and more // Add .ts extension for store, middleware and more
this.nuxt.options.extensions.push('ts') this.nuxt.options.extensions.push('ts')
// Extend build // Extend build

View File

@ -1,4 +1,4 @@
module.exports = { export default {
env: { env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000' baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}, },

View File

@ -1,4 +1,4 @@
module.exports = { export default {
css: ['uikit/dist/css/uikit.css'], css: ['uikit/dist/css/uikit.css'],
plugins: [ plugins: [
{ src: '~/plugins/uikit.js', ssr: false } { src: '~/plugins/uikit.js', ssr: false }

View File

@ -1,4 +1,4 @@
module.exports = { export default {
modules: ['@nuxtjs/apollo'], modules: ['@nuxtjs/apollo'],
apollo: { apollo: {
networkInterfaces: { networkInterfaces: {

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
title: 'Nuxt.js + Vue-ChartJS', title: 'Nuxt.js + Vue-ChartJS',
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
build: { build: {
babel: { babel: {
plugins: ['transform-decorators-legacy', 'transform-class-properties'] plugins: ['transform-decorators-legacy', 'transform-class-properties']

View File

@ -1,4 +1,4 @@
module.exports = { export default {
/* /*
** We set `spa` mode to have only client-side rendering ** We set `spa` mode to have only client-side rendering
*/ */

View File

@ -8,7 +8,7 @@ const modifyHtml = (html) => {
html = html.replace('</head>', ampScript + '</head>') html = html.replace('</head>', ampScript + '</head>')
return html return html
} }
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ charset: 'utf-8' }, { charset: 'utf-8' },

View File

@ -1,4 +1,4 @@
module.exports = { export default {
/* /*
** Customize the progress bar color ** Customize the progress bar color
*/ */

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
title: 'Nuxt-Cookies', title: 'Nuxt-Cookies',
meta: [ meta: [

View File

@ -1,4 +1,4 @@
module.exports = { export default {
/* /*
** Global CSS ** Global CSS
*/ */

View File

@ -1,4 +1,4 @@
module.exports = { export default {
loading: { loading: {
color: 'purple' color: 'purple'
} }

View File

@ -1,16 +1,14 @@
'use strict' import path from 'path'
import compress from 'compression'
const path = require('path') import cors from 'cors'
const compress = require('compression') import feathers from 'feathers'
const cors = require('cors') import configuration from 'feathers-configuration'
const feathers = require('feathers') import hooks from 'feathers-hooks'
const configuration = require('feathers-configuration') import rest from 'feathers-rest'
const hooks = require('feathers-hooks') import bodyParser from 'body-parser'
const rest = require('feathers-rest') import socketio from 'feathers-socketio'
const bodyParser = require('body-parser') import middleware from './middleware'
const socketio = require('feathers-socketio') import services from './services'
const middleware = require('./middleware')
const services = require('./services')
const app = feathers() const app = feathers()
@ -27,4 +25,4 @@ app.use(compress())
.configure(services) .configure(services)
.configure(middleware) .configure(middleware)
module.exports = app export default app

View File

@ -1,12 +1,10 @@
'use strict'
// Add any common hooks you want to share across services in here. // Add any common hooks you want to share across services in here.
// //
// Below is an example of how a hook is written and exported. Please // Below is an example of how a hook is written and exported. Please
// see http://docs.feathersjs.com/hooks/readme.html for more details // see http://docs.feathersjs.com/hooks/readme.html for more details
// on hooks. // on hooks.
exports.myHook = function (options) { export function myHook(options) {
return function (hook) { return function (hook) {
console.log('My custom global hook ran. Feathers is awesome!') // eslint-disable-line no-console console.log('My custom global hook ran. Feathers is awesome!') // eslint-disable-line no-console
} }

View File

@ -1,6 +1,5 @@
'use strict' import app from './app'
const app = require('./app')
const port = app.get('port') const port = app.get('port')
process.on('nuxt:build:done', (err) => { process.on('nuxt:build:done', (err) => {

View File

@ -1,8 +1,6 @@
'use strict' import nuxt from './nuxt'
const nuxt = require('./nuxt') export default function () {
module.exports = function () {
// Add your custom middleware here. Remember, that // Add your custom middleware here. Remember, that
// just like Express the order matters, so error // just like Express the order matters, so error
// handling middleware should go last. // handling middleware should go last.

View File

@ -1,5 +1,5 @@
const resolve = require('path').resolve import { resolve } from 'path'
const { Nuxt, Builder } = require('nuxt') import { Nuxt, Builder } from 'nuxt'
// Setup nuxt.js // Setup nuxt.js
let config = {} let config = {}
@ -18,6 +18,6 @@ if (config.dev) {
} }
// Add nuxt.js middleware // Add nuxt.js middleware
module.exports = function (req, res) { export default function (req, res) {
nuxt.render(req, res) nuxt.render(req, res)
} }

View File

@ -1,8 +1,6 @@
'use strict' import authentication from 'feathers-authentication'
const authentication = require('feathers-authentication') export default function () {
module.exports = function () {
const app = this const app = this
let config = app.get('auth') let config = app.get('auth')

View File

@ -1,8 +1,7 @@
'use strict' import authentication from './authentication'
const authentication = require('./authentication') import user from './user'
const user = require('./user')
module.exports = function () { export default function () {
const app = this const app = this
app.configure(authentication) app.configure(authentication)

View File

@ -1,8 +1,7 @@
'use strict' import hooks from 'feathers-hooks'
import { hooks as auth } from 'feathers-authentication'
require('../../../hooks') require('../../../hooks')
const hooks = require('feathers-hooks')
const auth = require('feathers-authentication').hooks
exports.before = { exports.before = {
all: [], all: [],

View File

@ -1,11 +1,9 @@
'use strict' import path from 'path'
import NeDB from 'nedb'
import service from 'feathers-nedb'
import hooks from './hooks'
const path = require('path') export default function () {
const NeDB = require('nedb')
const service = require('feathers-nedb')
const hooks = require('./hooks')
module.exports = function () {
const app = this const app = this
const db = new NeDB({ const db = new NeDB({

View File

@ -1,8 +1,6 @@
'use strict' import assert from 'assert'
import request from 'request'
const assert = require('assert') import app from '../src/app'
const request = require('request')
const app = require('../src/app')
describe('Feathers application tests', function () { describe('Feathers application tests', function () {
before(function (done) { before(function (done) {

View File

@ -1,7 +1,5 @@
'use strict' import assert from 'assert'
import app from '../../../src/app'
const assert = require('assert')
const app = require('../../../src/app')
describe('user service', function () { describe('user service', function () {
it('registered the users service', () => { it('registered the users service', () => {

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ charset: 'utf-8' }, { charset: 'utf-8' },

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ {

View File

@ -1,6 +1,6 @@
const path = require('path') import path from 'path'
const PurgecssPlugin = require('purgecss-webpack-plugin') import PurgecssPlugin from 'purgecss-webpack-plugin'
const glob = require('glob-all') import glob from 'glob-all'
class TailwindExtractor { class TailwindExtractor {
static extract(content) { static extract(content) {
@ -8,7 +8,7 @@ class TailwindExtractor {
} }
} }
module.exports = { export default {
build: { build: {
extractCSS: true, extractCSS: true,
postcss: [ postcss: [

View File

@ -127,7 +127,7 @@ var colors = {
'pink-lightest': '#ffebef' 'pink-lightest': '#ffebef'
} }
module.exports = { export default {
/* /*
|----------------------------------------------------------------------------- |-----------------------------------------------------------------------------

View File

@ -1,7 +1,10 @@
module.exports = function () { import http from 'http'
const server = require('http').createServer(this.nuxt.renderer.app) import socketIO from 'socket.io'
const io = require('socket.io')(server)
const server = http.createServer(this.nuxt.renderer.app)
const io = socketIO(server)
export default function () {
// overwrite nuxt.listen() // overwrite nuxt.listen()
this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve)) this.nuxt.listen = (port, host) => new Promise((resolve) => server.listen(port || 3000, host || 'localhost', resolve))
// close this server on 'close' event // close this server on 'close' event

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ charset: 'utf-8' }, { charset: 'utf-8' },

View File

@ -1,10 +1,15 @@
const { Nuxt, Builder } = require('nuxt') import { Nuxt, Builder } from 'nuxt'
const app = require('express')() import express from 'express'
const server = require('http').createServer(app) import http from 'http'
const io = require('socket.io')(server) import SocketIO from 'socket.io'
const port = process.env.PORT || 3000 const port = process.env.PORT || 3000
const isProd = process.env.NODE_ENV === 'production' const isProd = process.env.NODE_ENV === 'production'
const app = express()
const server = http.createServer(app)
const io = SocketIO(server)
// We instantiate Nuxt.js with the options // We instantiate Nuxt.js with the options
let config = require('./nuxt.config.js') let config = require('./nuxt.config.js')
config.dev = !isProd config.dev = !isProd

View File

@ -1,4 +1,4 @@
const hooks = require('require-extension-hooks') import hooks from 'require-extension-hooks'
// Setup browser environment // Setup browser environment
require('browser-env')() require('browser-env')()

View File

@ -1,4 +1,4 @@
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ {

View File

@ -1,6 +1,6 @@
const nodeExternals = require('webpack-node-externals') import nodeExternals from 'webpack-node-externals'
module.exports = { export default {
/* /*
** Head elements ** Head elements
** Add Roboto font and Material Icons ** Add Roboto font and Material Icons

View File

@ -1,7 +1,7 @@
const vuxLoader = require('vux-loader') import vuxLoader from 'vux-loader'
const path = require('path') import path from 'path'
module.exports = { export default {
head: { head: {
meta: [ meta: [
{ charset: 'utf-8' }, { charset: 'utf-8' },

View File

@ -1,29 +1,29 @@
const { promisify } = require('util') import { promisify } from 'util'
const _ = require('lodash') import _ from 'lodash'
const chokidar = require('chokidar') import chokidar from 'chokidar'
const { remove, readFile, writeFile, mkdirp, existsSync } = require('fs-extra') import { remove, readFile, writeFile, mkdirp, existsSync } from 'fs-extra'
const fs = require('fs') import fs from 'fs'
const hash = require('hash-sum') import hash from 'hash-sum'
const webpack = require('webpack') import webpack from 'webpack'
const serialize = require('serialize-javascript') import serialize from 'serialize-javascript'
const { join, resolve, basename, extname, dirname } = require('path') import { join, resolve, basename, extname, dirname } from 'path'
const MFS = require('memory-fs') import MFS from 'memory-fs'
const webpackDevMiddleware = require('webpack-dev-middleware') import webpackDevMiddleware from 'webpack-dev-middleware'
const webpackHotMiddleware = require('webpack-hot-middleware') import webpackHotMiddleware from 'webpack-hot-middleware'
const Debug = require('debug') import Debug from 'debug'
const Glob = require('glob') import Glob from 'glob'
const { r, wp, wChunk, createRoutes, parallel, relativeTo, waitFor, createSpinner } = require('../common/utils') import { r, wp, wChunk, createRoutes, parallel, relativeTo, waitFor, createSpinner } from '../common/utils'
const { Options } = require('../common') import Options from '../common/options'
const clientWebpackConfig = require('./webpack/client.config.js') import clientWebpackConfig from './webpack/client.config.js'
const serverWebpackConfig = require('./webpack/server.config.js') import serverWebpackConfig from './webpack/server.config.js'
const upath = require('upath') import upath from 'upath'
const debug = Debug('nuxt:build') const debug = Debug('nuxt:build')
debug.color = 2 // Force green color debug.color = 2 // Force green color
const glob = promisify(Glob) const glob = promisify(Glob)
module.exports = class Builder { export default class Builder {
constructor(nuxt) { constructor(nuxt) {
this.nuxt = nuxt this.nuxt = nuxt
this.isStatic = false // Flag to know if the build is for a generated app this.isStatic = false // Flag to know if the build is for a generated app
@ -156,7 +156,7 @@ module.exports = class Builder {
if (!options.babelrc && !options.presets) { if (!options.babelrc && !options.presets) {
options.presets = [ options.presets = [
[ [
require.resolve('babel-preset-vue-app'), 'babel-preset-vue-app',
{ {
targets: isServer ? { node: '8.0.0' } : { ie: 9, uglify: true } targets: isServer ? { node: '8.0.0' } : { ie: 9, uglify: true }
} }
@ -648,7 +648,7 @@ module.exports = class Builder {
const options = _.omit(this.options, Options.unsafeKeys) const options = _.omit(this.options, Options.unsafeKeys)
await writeFile( await writeFile(
config, config,
`module.exports = ${JSON.stringify(options, null, ' ')}`, `export default ${JSON.stringify(options, null, ' ')}`,
'utf8' 'utf8'
) )
} }

View File

@ -1,26 +1,11 @@
const { import _ from 'lodash'
copy, import { resolve, join, dirname, sep } from 'path'
remove, import { minify } from 'html-minifier'
writeFile, import Chalk from 'chalk'
mkdirp, import { copy, remove, writeFile, mkdirp, removeSync, existsSync } from 'fs-extra'
removeSync, import { isUrl, promisifyRoute, waitFor, flatRoutes, pe, printWarn, createSpinner } from '../common/utils'
existsSync
} = require('fs-extra')
const _ = require('lodash')
const { resolve, join, dirname, sep } = require('path')
const { minify } = require('html-minifier')
const Chalk = require('chalk')
const { printWarn, createSpinner } = require('../common/utils')
const { export default class Generator {
isUrl,
promisifyRoute,
waitFor,
flatRoutes,
pe
} = require('../common/utils')
module.exports = class Generator {
constructor(nuxt, builder) { constructor(nuxt, builder) {
this.nuxt = nuxt this.nuxt = nuxt
this.options = nuxt.options this.options = nuxt.options

View File

@ -1,7 +1,7 @@
const Builder = require('./builder') import Builder from './builder'
const Generator = require('./generator') import Generator from './generator'
module.exports = { export default {
Builder, Builder,
Generator Generator
} }

View File

@ -1,16 +1,16 @@
const ExtractTextPlugin = require('extract-text-webpack-plugin') import ExtractTextPlugin from 'extract-text-webpack-plugin'
const TimeFixPlugin = require('time-fix-plugin') import TimeFixPlugin from 'time-fix-plugin'
const WarnFixPlugin = require('./plugins/warnfix') import WarnFixPlugin from './plugins/warnfix'
const ProgressPlugin = require('./plugins/progress') import ProgressPlugin from './plugins/progress'
const webpack = require('webpack') import webpack from 'webpack'
const { cloneDeep } = require('lodash') import { cloneDeep } from 'lodash'
const { join, resolve } = require('path') import { join, resolve } from 'path'
const { isUrl, urlJoin } = require('../../common/utils') import { isUrl, urlJoin } from '../../common/utils'
const vueLoader = require('./vue-loader') import vueLoader from './vue-loader'
const styleLoader = require('./style-loader') import styleLoader from './style-loader'
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -20,7 +20,7 @@ const styleLoader = require('./style-loader')
| webpack config files | webpack config files
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
module.exports = function webpackBaseConfig({ name, isServer }) { export default function webpackBaseConfig({ name, isServer }) {
// Prioritize nested node_modules in webpack search path (#2558) // Prioritize nested node_modules in webpack search path (#2558)
const webpackModulesDir = ['node_modules'].concat(this.options.modulesDir) const webpackModulesDir = ['node_modules'].concat(this.options.modulesDir)

View File

@ -1,19 +1,19 @@
const { each } = require('lodash') import { each } from 'lodash'
const webpack = require('webpack') import webpack from 'webpack'
// const VueSSRClientPlugin = require('vue-server-renderer/client-plugin') // import VueSSRClientPlugin from 'vue-server-renderer/client-plugin'
const VueSSRClientPlugin = require('./plugins/vue/client') import VueSSRClientPlugin from './plugins/vue/client'
const HTMLPlugin = require('html-webpack-plugin') import HTMLPlugin from 'html-webpack-plugin'
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin') import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
const StylishPlugin = require('webpack-stylish') import StylishPlugin from 'webpack-stylish'
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
const { resolve } = require('path') import { resolve } from 'path'
const Debug = require('debug') import Debug from 'debug'
const base = require('./base.config.js') import base from './base.config.js'
const debug = Debug('nuxt:build') const debug = Debug('nuxt:build')
debug.color = 2 // Force green color debug.color = 2 // Force green color
module.exports = function webpackClientConfig() { export default function webpackClientConfig() {
let config = base.call(this, { name: 'client', isServer: false }) let config = base.call(this, { name: 'client', isServer: false })
// Entry points // Entry points

View File

@ -1,12 +1,12 @@
const webpack = require('webpack') import webpack from 'webpack'
const chalk = require('chalk') import chalk from 'chalk'
const _ = require('lodash') import _ from 'lodash'
const sharedState = {} const sharedState = {}
const BLOCK_CHAR = '█' const BLOCK_CHAR = '█'
module.exports = class ProgressPlugin extends webpack.ProgressPlugin { export default class ProgressPlugin extends webpack.ProgressPlugin {
constructor(options) { constructor(options) {
super(options) super(options)

View File

@ -1,8 +1,8 @@
const hash = require('hash-sum') import hash from 'hash-sum'
const uniq = require('lodash.uniq') import uniq from 'lodash.uniq'
const { isJS, onEmit } = require('./util') import { isJS, onEmit } from './util'
module.exports = class VueSSRClientPlugin { export default class VueSSRClientPlugin {
constructor(options = {}) { constructor(options = {}) {
this.options = Object.assign({ this.options = Object.assign({
filename: 'vue-ssr-client-manifest.json' filename: 'vue-ssr-client-manifest.json'

View File

@ -1,6 +1,6 @@
const { validate, isJS, onEmit } = require('./util') import { validate, isJS, onEmit } from './util'
module.exports = class VueSSRServerPlugin { export default class VueSSRServerPlugin {
constructor(options = {}) { constructor(options = {}) {
this.options = Object.assign({ this.options = Object.assign({
filename: 'vue-ssr-server-bundle.json' filename: 'vue-ssr-server-bundle.json'

View File

@ -1,10 +1,10 @@
const { red, yellow } = require('chalk') import chalk from 'chalk'
const prefix = `[vue-server-renderer-webpack-plugin]` const prefix = `[vue-server-renderer-webpack-plugin]`
const warn = exports.warn = msg => console.error(red(`${prefix} ${msg}\n`)) // eslint-disable-line no-console export const warn = msg => console.error(chalk.red(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
const tip = exports.tip = msg => console.log(yellow(`${prefix} ${msg}\n`)) // eslint-disable-line no-console export const tip = msg => console.log(chalk.yellow(`${prefix} ${msg}\n`)) // eslint-disable-line no-console
exports.validate = compiler => { export const validate = compiler => {
if (compiler.options.target !== 'node') { if (compiler.options.target !== 'node') {
warn('webpack config `target` should be "node".') warn('webpack config `target` should be "node".')
} }
@ -21,7 +21,7 @@ exports.validate = compiler => {
} }
} }
exports.onEmit = (compiler, name, hook) => { export const onEmit = (compiler, name, hook) => {
if (compiler.hooks) { if (compiler.hooks) {
// Webpack >= 4.0.0 // Webpack >= 4.0.0
compiler.hooks.emit.tap(name, compiler.hooks.emit.tap(name,
@ -38,6 +38,6 @@ exports.onEmit = (compiler, name, hook) => {
} }
} }
exports.isJS = (file) => /\.js(\?[^.]+)?$/.test(file) export const isJS = (file) => /\.js(\?[^.]+)?$/.test(file)
exports.isCSS = (file) => /\.css(\?[^.]+)?$/.test(file) export const isCSS = (file) => /\.css(\?[^.]+)?$/.test(file)

View File

@ -1,4 +1,4 @@
module.exports = class WarnFixPlugin { export default class WarnFixPlugin {
apply(compiler) /* istanbul ignore next */ { apply(compiler) /* istanbul ignore next */ {
compiler.hooks.done.tap('warnfix-plugin', stats => { compiler.hooks.done.tap('warnfix-plugin', stats => {
stats.compilation.warnings = stats.compilation.warnings.filter(warn => { stats.compilation.warnings = stats.compilation.warnings.filter(warn => {

View File

@ -1,10 +1,10 @@
const { existsSync } = require('fs') import { existsSync } from 'fs'
const { resolve, join } = require('path') import { resolve, join } from 'path'
const { cloneDeep } = require('lodash') import { cloneDeep } from 'lodash'
const { isPureObject } = require('../../common/utils') import { isPureObject } from '../../common/utils'
const createResolver = require('postcss-import-resolver') import createResolver from 'postcss-import-resolver'
module.exports = function postcssConfig() { export default function postcssConfig() {
let config = cloneDeep(this.options.build.postcss) let config = cloneDeep(this.options.build.postcss)
/* istanbul ignore if */ /* istanbul ignore if */
@ -78,7 +78,7 @@ module.exports = function postcssConfig() {
if (isPureObject(config) && isPureObject(config.plugins)) { if (isPureObject(config) && isPureObject(config.plugins)) {
config.plugins = Object.keys(config.plugins) config.plugins = Object.keys(config.plugins)
.map(p => { .map(p => {
const plugin = require(this.nuxt.resolvePath(p)) const plugin = this.nuxt.requireModule(p)
const opts = config.plugins[p] const opts = config.plugins[p]
if (opts === false) return // Disabled if (opts === false) return // Disabled
const instance = plugin(opts) const instance = plugin(opts)

View File

@ -1,18 +1,18 @@
const webpack = require('webpack') import webpack from 'webpack'
// const VueSSRServerPlugin = require('vue-server-renderer/server-plugin') // import VueSSRServerPlugin from 'vue-server-renderer/server-plugin'
const VueSSRServerPlugin = require('./plugins/vue/server') import VueSSRServerPlugin from './plugins/vue/server'
const nodeExternals = require('webpack-node-externals') import nodeExternals from 'webpack-node-externals'
const { each } = require('lodash') import { each } from 'lodash'
const { resolve } = require('path') import { resolve } from 'path'
const { existsSync } = require('fs') import { existsSync } from 'fs'
const base = require('./base.config.js') import base from './base.config.js'
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Webpack Server Config | Webpack Server Config
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
module.exports = function webpackServerConfig() { export default function webpackServerConfig() {
let config = base.call(this, { name: 'server', isServer: true }) let config = base.call(this, { name: 'server', isServer: true })
// Env object defined in nuxt.config.js // Env object defined in nuxt.config.js

View File

@ -1,8 +1,8 @@
const ExtractTextPlugin = require('extract-text-webpack-plugin') import ExtractTextPlugin from 'extract-text-webpack-plugin'
const { join } = require('path') import { join } from 'path'
const postcssConfig = require('./postcss') import postcssConfig from './postcss'
module.exports = function styleLoader(ext, loaders = [], isVueLoader = false) { export default function styleLoader(ext, loaders = [], isVueLoader = false) {
const sourceMap = Boolean(this.options.build.cssSourceMap) const sourceMap = Boolean(this.options.build.cssSourceMap)
// Normalize loaders // Normalize loaders

View File

@ -1,7 +1,7 @@
const postcssConfig = require('./postcss') import postcssConfig from './postcss'
const styleLoader = require('./style-loader') import styleLoader from './style-loader'
module.exports = function vueLoader({ isServer }) { export default function vueLoader({ isServer }) {
// https://vue-loader.vuejs.org/en // https://vue-loader.vuejs.org/en
const config = { const config = {
postcss: postcssConfig.call(this), postcss: postcssConfig.call(this),

View File

@ -1,7 +0,0 @@
const Utils = require('./utils')
const Options = require('./options')
module.exports = {
Utils,
Options
}

8
lib/common/module.js Normal file
View File

@ -0,0 +1,8 @@
const esm = require('esm')
const _esm = esm(module, {})
exports.requireModule = function requireModule() {
const m = _esm.apply(this, arguments)
return (m && m.default) || m
}

View File

@ -1,15 +1,15 @@
const _ = require('lodash') import _ from 'lodash'
const Debug = require('debug') import Debug from 'debug'
const { join, resolve } = require('path') import { join, resolve } from 'path'
const { existsSync, readdirSync } = require('fs') import { existsSync, readdirSync } from 'fs'
const { isUrl, isPureObject } = require('../common/utils') import { isUrl, isPureObject } from '../common/utils'
const debug = Debug('nuxt:build') const debug = Debug('nuxt:build')
debug.color = 2 // Force green color debug.color = 2 // Force green color
const Options = {} const Options = {}
module.exports = Options export default Options
Options.from = function (_options) { Options.from = function (_options) {
// Clone options to prevent unwanted side-effects // Clone options to prevent unwanted side-effects

View File

@ -1,35 +1,35 @@
const { resolve, relative, sep } = require('path') import { resolve, relative, sep } from 'path'
const _ = require('lodash') import _ from 'lodash'
const PrettyError = require('pretty-error') import PrettyError from 'pretty-error'
const Chalk = require('chalk') import Chalk from 'chalk'
const ORA = require('ora') import ORA from 'ora'
exports.pe = new PrettyError() export const pe = new PrettyError()
exports.printWarn = function (msg, from) { export const printWarn = function (msg, from) {
/* eslint-disable no-console */ /* eslint-disable no-console */
const fromStr = from ? Chalk.yellow(` ${from}\n\n`) : ' ' const fromStr = from ? Chalk.yellow(` ${from}\n\n`) : ' '
console.warn('\n' + Chalk.bgYellow.black(' WARN ') + fromStr + msg + '\n') console.warn('\n' + Chalk.bgYellow.black(' WARN ') + fromStr + msg + '\n')
} }
exports.renderError = function (_error, from) { export const renderError = function (_error, from) {
const errStr = exports.pe.render(_error) const errStr = pe.render(_error)
const fromStr = from ? Chalk.red(` ${from}`) : '' const fromStr = from ? Chalk.red(` ${from}`) : ''
return '\n' + Chalk.bgRed.black(' ERROR ') + fromStr + '\n\n' + errStr return '\n' + Chalk.bgRed.black(' ERROR ') + fromStr + '\n\n' + errStr
} }
exports.printError = function () { export const printError = function () {
/* eslint-disable no-console */ /* eslint-disable no-console */
console.error(exports.renderError(...arguments)) console.error(renderError(...arguments))
} }
exports.fatalError = function () { export const fatalError = function () {
/* eslint-disable no-console */ /* eslint-disable no-console */
console.error(exports.renderError(...arguments)) console.error(renderError(...arguments))
process.exit(1) process.exit(1)
} }
exports.createSpinner = function () { export const createSpinner = function () {
return new ORA({ return new ORA({
color: 'green', color: 'green',
spinner: 'clock', spinner: 'clock',
@ -37,15 +37,15 @@ exports.createSpinner = function () {
}) })
} }
exports.encodeHtml = function encodeHtml(str) { export const encodeHtml = function encodeHtml(str) {
return str.replace(/</g, '&lt;').replace(/>/g, '&gt;') return str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
} }
exports.getContext = function getContext(req, res) { export const getContext = function getContext(req, res) {
return { req, res } return { req, res }
} }
exports.setAnsiColors = function setAnsiColors(ansiHTML) { export const setAnsiColors = function setAnsiColors(ansiHTML) {
ansiHTML.setColors({ ansiHTML.setColors({
reset: ['efefef', 'a6004c'], reset: ['efefef', 'a6004c'],
darkgrey: '5a012b', darkgrey: '5a012b',
@ -58,7 +58,7 @@ exports.setAnsiColors = function setAnsiColors(ansiHTML) {
}) })
} }
exports.waitFor = function waitFor(ms) { export const waitFor = function waitFor(ms) {
return new Promise(resolve => setTimeout(resolve, ms || 0)) return new Promise(resolve => setTimeout(resolve, ms || 0))
} }
@ -76,9 +76,7 @@ async function promiseFinally(fn, finalFn) {
return result return result
} }
exports.promiseFinally = promiseFinally export const timeout = function timeout(fn, ms, msg) {
exports.timeout = function timeout(fn, ms, msg) {
let timerId let timerId
const warpPromise = promiseFinally(fn, () => clearTimeout(timerId)) const warpPromise = promiseFinally(fn, () => clearTimeout(timerId))
const timerPromise = new Promise((resolve, reject) => { const timerPromise = new Promise((resolve, reject) => {
@ -87,7 +85,7 @@ exports.timeout = function timeout(fn, ms, msg) {
return Promise.race([warpPromise, timerPromise]) return Promise.race([warpPromise, timerPromise])
} }
exports.urlJoin = function urlJoin() { export const urlJoin = function urlJoin() {
return [].slice return [].slice
.call(arguments) .call(arguments)
.join('/') .join('/')
@ -95,11 +93,11 @@ exports.urlJoin = function urlJoin() {
.replace(':/', '://') .replace(':/', '://')
} }
exports.isUrl = function isUrl(url) { export const isUrl = function isUrl(url) {
return url.indexOf('http') === 0 || url.indexOf('//') === 0 return url.indexOf('http') === 0 || url.indexOf('//') === 0
} }
exports.promisifyRoute = function promisifyRoute(fn, ...args) { export const promisifyRoute = function promisifyRoute(fn, ...args) {
// If routes is an array // If routes is an array
if (Array.isArray(fn)) { if (Array.isArray(fn)) {
return Promise.resolve(fn) return Promise.resolve(fn)
@ -125,18 +123,18 @@ exports.promisifyRoute = function promisifyRoute(fn, ...args) {
return promise return promise
} }
exports.sequence = function sequence(tasks, fn) { export const sequence = function sequence(tasks, fn) {
return tasks.reduce( return tasks.reduce(
(promise, task) => promise.then(() => fn(task)), (promise, task) => promise.then(() => fn(task)),
Promise.resolve() Promise.resolve()
) )
} }
exports.parallel = function parallel(tasks, fn) { export const parallel = function parallel(tasks, fn) {
return Promise.all(tasks.map(task => fn(task))) return Promise.all(tasks.map(task => fn(task)))
} }
exports.chainFn = function chainFn(base, fn) { export const chainFn = function chainFn(base, fn) {
/* istanbul ignore if */ /* istanbul ignore if */
if (!(fn instanceof Function)) { if (!(fn instanceof Function)) {
return return
@ -163,21 +161,21 @@ exports.chainFn = function chainFn(base, fn) {
} }
} }
exports.isPureObject = function isPureObject(o) { export const isPureObject = function isPureObject(o) {
return !Array.isArray(o) && typeof o === 'object' return !Array.isArray(o) && typeof o === 'object'
} }
const isWindows = (exports.isWindows = /^win/.test(process.platform)) export const isWindows = /^win/.test(process.platform)
const wp = (exports.wp = function wp(p = '') { export const wp = function wp(p = '') {
/* istanbul ignore if */ /* istanbul ignore if */
if (isWindows) { if (isWindows) {
return p.replace(/\\/g, '\\\\') return p.replace(/\\/g, '\\\\')
} }
return p return p
}) }
exports.wChunk = function wChunk(p = '') { export const wChunk = function wChunk(p = '') {
/* istanbul ignore if */ /* istanbul ignore if */
if (isWindows) { if (isWindows) {
return p.replace(/\//g, '_') return p.replace(/\//g, '_')
@ -189,7 +187,7 @@ const reqSep = /\//g
const sysSep = _.escapeRegExp(sep) const sysSep = _.escapeRegExp(sep)
const normalize = string => string.replace(reqSep, sysSep) const normalize = string => string.replace(reqSep, sysSep)
const r = (exports.r = function r() { export const r = function r() {
let args = Array.prototype.slice.apply(arguments) let args = Array.prototype.slice.apply(arguments)
let lastArg = _.last(args) let lastArg = _.last(args)
@ -198,9 +196,9 @@ const r = (exports.r = function r() {
} }
return wp(resolve(...args.map(normalize))) return wp(resolve(...args.map(normalize)))
}) }
exports.relativeTo = function relativeTo() { export const relativeTo = function relativeTo() {
let args = Array.prototype.slice.apply(arguments) let args = Array.prototype.slice.apply(arguments)
let dir = args.shift() let dir = args.shift()
@ -220,7 +218,7 @@ exports.relativeTo = function relativeTo() {
return wp(rp) return wp(rp)
} }
exports.flatRoutes = function flatRoutes(router, path = '', routes = []) { export const flatRoutes = function flatRoutes(router, path = '', routes = []) {
router.forEach(r => { router.forEach(r => {
if (!r.path.includes(':') && !r.path.includes('*')) { if (!r.path.includes(':') && !r.path.includes('*')) {
/* istanbul ignore if */ /* istanbul ignore if */
@ -288,7 +286,7 @@ function cleanChildrenRoutes(routes, isChild = false) {
return routes return routes
} }
exports.createRoutes = function createRoutes(files, srcDir, pagesDir) { export const createRoutes = function createRoutes(files, srcDir, pagesDir) {
let routes = [] let routes = []
files.forEach(file => { files.forEach(file => {
let keys = file let keys = file

View File

@ -1,12 +1,9 @@
const { Options, Utils } = require('../common') import Module from './module'
const Module = require('./module') import Nuxt from './nuxt'
const Nuxt = require('./nuxt') import Renderer from './renderer'
const Renderer = require('./renderer')
module.exports = { export default {
Nuxt, Nuxt,
Module, Module,
Renderer, Renderer
Options,
Utils
} }

View File

@ -1,9 +1,9 @@
const Vue = require('vue') import Vue from 'vue'
const VueMeta = require('vue-meta') import VueMeta from 'vue-meta'
const VueServerRenderer = require('vue-server-renderer') import VueServerRenderer from 'vue-server-renderer'
const LRU = require('lru-cache') import LRU from 'lru-cache'
module.exports = class MetaRenderer { export default class MetaRenderer {
constructor(nuxt, renderer) { constructor(nuxt, renderer) {
this.nuxt = nuxt this.nuxt = nuxt
this.renderer = renderer this.renderer = renderer

View File

@ -1,8 +1,8 @@
const Youch = require('@nuxtjs/youch') import Youch from '@nuxtjs/youch'
const { join, resolve, relative, isAbsolute } = require('path') import { join, resolve, relative, isAbsolute } from 'path'
const { readFile } = require('fs-extra') import { readFile } from 'fs-extra'
module.exports = function errorMiddleware(err, req, res, next) { export default function errorMiddleware(err, req, res, next) {
// ensure statusCode, message and name fields // ensure statusCode, message and name fields
err.statusCode = err.statusCode || 500 err.statusCode = err.statusCode || 500
err.message = err.message || 'Nuxt Server Error' err.message = err.message || 'Nuxt Server Error'

View File

@ -1,9 +1,9 @@
const generateETag = require('etag') import generateETag from 'etag'
const fresh = require('fresh') import fresh from 'fresh'
const { getContext } = require('../../common/utils') import { getContext } from '../../common/utils'
module.exports = async function nuxtMiddleware(req, res, next) { export default async function nuxtMiddleware(req, res, next) {
// Get context // Get context
const context = getContext(req, res) const context = getContext(req, res)

View File

@ -1,9 +1,9 @@
const path = require('path') import path from 'path'
const fs = require('fs') import fs from 'fs'
const hash = require('hash-sum') import hash from 'hash-sum'
const { chainFn, sequence, printWarn } = require('../common/utils') import { chainFn, sequence, printWarn } from '../common/utils'
module.exports = class ModuleContainer { export default class ModuleContainer {
constructor(nuxt) { constructor(nuxt) {
this.nuxt = nuxt this.nuxt = nuxt
this.options = nuxt.options this.options = nuxt.options
@ -112,7 +112,7 @@ module.exports = class ModuleContainer {
// Resolve handler // Resolve handler
if (!handler) { if (!handler) {
handler = require(this.nuxt.resolvePath(src)) handler = this.nuxt.requireModule(src)
} }
// Validate handler // Validate handler

View File

@ -1,20 +1,21 @@
const Debug = require('debug') import Debug from 'debug'
const enableDestroy = require('server-destroy') import enableDestroy from 'server-destroy'
const Module = require('module') import Module from 'module'
const { isPlainObject } = require('lodash') import { isPlainObject } from 'lodash'
const chalk = require('chalk') import chalk from 'chalk'
const { existsSync } = require('fs-extra') import { existsSync } from 'fs-extra'
const { Options } = require('../common') import Options from '../common/options'
const { sequence, printError } = require('../common/utils') import { sequence, printError } from '../common/utils'
const { resolve, join } = require('path') import { resolve, join } from 'path'
const { version } = require('../../package.json') import { version } from '../../package.json'
const ModuleContainer = require('./module') import ModuleContainer from './module'
const Renderer = require('./renderer') import Renderer from './renderer'
import { requireModule } from '../common/module'
const debug = Debug('nuxt:') const debug = Debug('nuxt:')
debug.color = 5 debug.color = 5
module.exports = class Nuxt { export default class Nuxt {
constructor(options = {}) { constructor(options = {}) {
this.options = Options.from(options) this.options = Options.from(options)
@ -196,6 +197,10 @@ module.exports = class Nuxt {
throw new Error(`Cannot resolve "${path}" from "${_path}"`) throw new Error(`Cannot resolve "${path}" from "${_path}"`)
} }
requireModule(name) {
return requireModule(this.resolvePath(name))
}
async close(callback) { async close(callback) {
await this.callHook('close', this) await this.callHook('close', this)

View File

@ -1,22 +1,22 @@
const ansiHTML = require('ansi-html') import ansiHTML from 'ansi-html'
const serialize = require('serialize-javascript') import serialize from 'serialize-javascript'
const serveStatic = require('serve-static') import serveStatic from 'serve-static'
const compression = require('compression') import compression from 'compression'
const _ = require('lodash') import _ from 'lodash'
const { join, resolve } = require('path') import { join, resolve } from 'path'
const fs = require('fs-extra') import fs from 'fs-extra'
const { createBundleRenderer } = require('vue-server-renderer') import { createBundleRenderer } from 'vue-server-renderer'
const Debug = require('debug') import Debug from 'debug'
const connect = require('connect') import connect from 'connect'
const launchMiddleware = require('launch-editor-middleware') import launchMiddleware from 'launch-editor-middleware'
const crypto = require('crypto') import crypto from 'crypto'
const { setAnsiColors, isUrl, waitFor, timeout } = require('../common/utils') import { setAnsiColors, isUrl, waitFor, timeout } from '../common/utils'
const { Options } = require('../common') import Options from '../common/options'
const MetaRenderer = require('./meta') import MetaRenderer from './meta'
const errorMiddleware = require('./middleware/error') import errorMiddleware from './middleware/error'
const nuxtMiddleware = require('./middleware/nuxt') import nuxtMiddleware from './middleware/nuxt'
const debug = Debug('nuxt:render') const debug = Debug('nuxt:render')
debug.color = 4 // Force blue color debug.color = 4 // Force blue color
@ -25,7 +25,7 @@ setAnsiColors(ansiHTML)
let jsdom = null let jsdom = null
module.exports = class Renderer { export default class Renderer {
constructor(nuxt) { constructor(nuxt) {
this.nuxt = nuxt this.nuxt = nuxt
this.options = nuxt.options this.options = nuxt.options
@ -180,12 +180,10 @@ module.exports = class Renderer {
const $m = m const $m = m
let src let src
if (typeof m === 'string') { if (typeof m === 'string') {
src = this.nuxt.resolvePath(m) m = this.nuxt.requireModule(m)
m = require(src)
} }
if (typeof m.handler === 'string') { if (typeof m.handler === 'string') {
src = this.nuxt.resolvePath(m.handler) m.handler = this.nuxt.requireModule(m.handler)
m.handler = require(src)
} }
const handler = m.handler || m const handler = m.handler || m

View File

@ -1,11 +1,20 @@
/*! /*!
* Nuxt.js * Nuxt.js
* (c) 2016-2017 Chopin Brothers * (c) 2016-2018 Chopin Brothers
* Core maintainer: Pooya Parsa (@pi0) * Core maintainers: Pooya Parsa (@pi0) - Clark Du (@clarkdo)
* Released under the MIT License. * Released under the MIT License.
*/ */
const core = require('./core') const requireModule = require('esm')(module, {})
const builder = require('./builder')
module.exports = Object.assign({}, core, builder) const core = requireModule('./core').default
const builder = requireModule('./builder').default
const Utils = requireModule('./common/utils')
const Options = requireModule('./common/options').default
module.exports = {
Utils,
Options,
...core,
...builder
}

18
lib/index.mjs Normal file
View File

@ -0,0 +1,18 @@
/*!
* Nuxt.js
* (c) 2016-2018 Chopin Brothers
* Core maintainers: Pooya Parsa (@pi0) - Clark Du (@clarkdo)
* Released under the MIT License.
*/
import core from './core'
import builder from './builder'
import * as Utils from './common/utils'
import Options from './common/options'
export default {
Utils,
Options,
...core,
...builder
}

View File

@ -14,6 +14,7 @@
} }
], ],
"main": "./lib/index.js", "main": "./lib/index.js",
"module": "./lib/index.mjs",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
"type": "git", "type": "git",

View File

@ -8,6 +8,7 @@ import finalhandler from 'finalhandler'
import rp from 'request-promise-native' import rp from 'request-promise-native'
import { interceptLog, release } from './helpers/console' import { interceptLog, release } from './helpers/console'
import { Nuxt, Builder, Generator } from '..' import { Nuxt, Builder, Generator } from '..'
import { loadConfig } from './helpers/config'
const port = 4002 const port = 4002
const url = route => 'http://localhost:' + port + route const url = route => 'http://localhost:' + port + route
@ -19,10 +20,11 @@ let generator = null
// Init nuxt.js and create server listening on localhost:4000 // Init nuxt.js and create server listening on localhost:4000
test.serial('Init Nuxt.js', async t => { test.serial('Init Nuxt.js', async t => {
let config = require(resolve(rootDir, 'nuxt.config.js')) const config = loadConfig('basic', {
config.rootDir = rootDir buildDir: '.nuxt-generate',
config.buildDir = '.nuxt-generate' dev: false
config.dev = false })
config.build.stats = false config.build.stats = false
const logSpy = await interceptLog(async () => { const logSpy = await interceptLog(async () => {

View File

@ -1,8 +1,8 @@
import test from 'ava' import test from 'ava'
import { resolve } from 'path'
import rp from 'request-promise-native' import rp from 'request-promise-native'
import { Nuxt, Builder } from '..' import { Nuxt, Builder } from '..'
import { interceptLog } from './helpers/console' import { interceptLog } from './helpers/console'
import { loadConfig } from './helpers/config'
const port = 4007 const port = 4007
const url = route => 'http://localhost:' + port + route const url = route => 'http://localhost:' + port + route
@ -12,10 +12,7 @@ let builder = null
// Init nuxt.js and create server listening on localhost:4000 // Init nuxt.js and create server listening on localhost:4000
test.before('Init Nuxt.js', async t => { test.before('Init Nuxt.js', async t => {
const rootDir = resolve(__dirname, 'fixtures/custom-dirs') const config = loadConfig('/custom-dirs', { dev: false })
let config = require(resolve(rootDir, 'nuxt.config.js'))
config.rootDir = rootDir
config.dev = false
const logSpy = await interceptLog(async () => { const logSpy = await interceptLog(async () => {
nuxt = new Nuxt(config) nuxt = new Nuxt(config)

View File

@ -1,8 +1,8 @@
import test from 'ava' import test from 'ava'
import { resolve } from 'path'
import rp from 'request-promise-native' import rp from 'request-promise-native'
import { Nuxt, Builder } from '..' import { Nuxt, Builder } from '..'
import { interceptLog, interceptError, release } from './helpers/console' import { interceptLog, interceptError, release } from './helpers/console'
import { loadConfig } from './helpers/config'
const port = 4009 const port = 4009
const url = route => 'http://localhost:' + port + route const url = route => 'http://localhost:' + port + route
@ -11,9 +11,7 @@ let nuxt = null
// Init nuxt.js and create server listening on localhost:4000 // Init nuxt.js and create server listening on localhost:4000
test.before('Init Nuxt.js', async t => { test.before('Init Nuxt.js', async t => {
const rootDir = resolve(__dirname, 'fixtures/debug') const config = loadConfig('debug')
let config = require(resolve(rootDir, 'nuxt.config.js'))
config.rootDir = rootDir
const logSpy = await interceptLog(async () => { const logSpy = await interceptLog(async () => {
nuxt = new Nuxt(config) nuxt = new Nuxt(config)

View File

@ -1,7 +1,7 @@
import test from 'ava' import test from 'ava'
import { resolve } from 'path'
import { Nuxt, Builder } from '..' import { Nuxt, Builder } from '..'
import { intercept } from './helpers/console' import { intercept } from './helpers/console'
import { loadConfig } from './helpers/config'
const port = 4010 const port = 4010
@ -11,10 +11,7 @@ let buildSpies = null
// Init nuxt.js and create server listening on localhost:4000 // Init nuxt.js and create server listening on localhost:4000
test.serial('Init Nuxt.js', async t => { test.serial('Init Nuxt.js', async t => {
const rootDir = resolve(__dirname, 'fixtures/deprecate') const config = loadConfig('deprecate', { dev: false })
let config = require(resolve(rootDir, 'nuxt.config.js'))
config.rootDir = rootDir
config.dev = false
buildSpies = await intercept(async () => { buildSpies = await intercept(async () => {
nuxt = new Nuxt(config) nuxt = new Nuxt(config)

View File

@ -1,8 +1,8 @@
import test from 'ava' import test from 'ava'
import { resolve } from 'path'
import rp from 'request-promise-native' import rp from 'request-promise-native'
import { Nuxt, Builder } from '..' import { Nuxt, Builder } from '..'
import { interceptLog, interceptError, release } from './helpers/console' import { interceptLog, interceptError, release } from './helpers/console'
import { loadConfig } from './helpers/config'
const port = 4005 const port = 4005
const url = route => 'http://localhost:' + port + route const url = route => 'http://localhost:' + port + route
@ -12,10 +12,7 @@ let logSpy
// Init nuxt.js and create server listening on localhost:4000 // Init nuxt.js and create server listening on localhost:4000
test.serial('Init Nuxt.js', async t => { test.serial('Init Nuxt.js', async t => {
const rootDir = resolve(__dirname, 'fixtures/error') const config = loadConfig('error', { dev: false })
const config = require(resolve(rootDir, 'nuxt.config.js'))
config.rootDir = rootDir
config.dev = false
logSpy = await interceptLog(async () => { logSpy = await interceptLog(async () => {
nuxt = new Nuxt(config) nuxt = new Nuxt(config)

View File

@ -7,10 +7,10 @@ import finalhandler from 'finalhandler'
import rp from 'request-promise-native' import rp from 'request-promise-native'
import { intercept, interceptLog } from './helpers/console' import { intercept, interceptLog } from './helpers/console'
import { Nuxt, Builder, Generator, Options } from '..' import { Nuxt, Builder, Generator, Options } from '..'
import { loadConfig } from './helpers/config'
const port = 4015 const port = 4015
const url = route => 'http://localhost:' + port + route const url = route => 'http://localhost:' + port + route
const rootDir = resolve(__dirname, 'fixtures/basic')
let nuxt = null let nuxt = null
let server = null let server = null
@ -18,10 +18,10 @@ let generator = null
// Init nuxt.js and create server listening on localhost:4015 // Init nuxt.js and create server listening on localhost:4015
test.serial('Init Nuxt.js', async t => { test.serial('Init Nuxt.js', async t => {
let config = require(resolve(rootDir, 'nuxt.config.js')) let config = loadConfig('basic', {
config.rootDir = rootDir buildDir: '.nuxt-spa-fallback',
config.buildDir = '.nuxt-spa-fallback' dev: false
config.dev = false })
config.build.stats = false config.build.stats = false
const logSpy = await interceptLog(async () => { const logSpy = await interceptLog(async () => {

Some files were not shown because too many files have changed in this diff Show More