Skip to content

Commit

Permalink
feat: move nuxt-legacy and nuxt-start into packages (nuxt#3824)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 31, 2018
1 parent 4311aca commit f854653
Show file tree
Hide file tree
Showing 32 changed files with 591 additions and 362 deletions.
5 changes: 3 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ jobs:
at: ~/project
- run:
name: Build Fixtures
command: yarn build && yarn test:fixtures -w=4 --coverage && yarn coverage
command: EDGE_BUILD=1 yarn build && yarn test:fixtures -w=4 --coverage && yarn coverage
- persist_to_workspace:
root: ~/project
paths:
Expand Down Expand Up @@ -90,7 +90,8 @@ jobs:
command: |
echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
echo "//registry.yarnpkg.com/:_authToken=$NPM_TOKEN" >> ~/.npmrc
./scripts/release-edge
npm publish
for p in packages/*; do cd $p ; npm publish ; cd - ; done
workflows:
version: 2
Expand Down
21 changes: 21 additions & 0 deletions build/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import path from 'path'
import Package from './package'

// Commons
const rootDir = path.resolve(__dirname, '..')

// Force NODE_ENV to production
process.env.NODE_ENV = 'production'

// Packages
const packages = [
'.',
'packages/nuxt-start',
'packages/nuxt-legacy'
]

// Build all packages
packages
.map(p => path.resolve(rootDir, p))
.map(p => new Package({ rootDir: path.resolve(rootDir, p) }))
.forEach(pkg => pkg.build())
23 changes: 23 additions & 0 deletions build/builtins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
** Core logic from https://github.com/sindresorhus/builtin-modules
** Many thanks to @sindresorhus
*/
const { builtinModules } = require('module')

const blacklist = [
'sys'
]

const builtins = (builtinModules || Object.keys(process.binding('natives')))
.filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x) && !blacklist.includes(x))
.sort()

let builtinsObj = null

const convertToObj = () => builtins.reduce((obj, builtin) => {
obj[builtin] = true
return obj
}, (builtinsObj = {}))

export const builtinsMap = () => builtinsObj || convertToObj()
export default builtins
214 changes: 214 additions & 0 deletions build/package.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import { resolve } from 'path'
import { spawnSync } from 'child_process'
import EventEmitter from 'events'
import consola from 'consola'
import { readFileSync, existsSync, readJSONSync, writeFileSync, copySync, removeSync } from 'fs-extra'
import { builtinsMap } from './builtins'

const DEFAULTS = {
distDir: 'dist',
edge: Boolean(process.env.EDGE_BUILD)
}

export default class Package extends EventEmitter {
constructor(options) {
super()

// Assign options
Object.assign(this, DEFAULTS, options)

this.rootDir = this.rootDir || process.cwd()
this.distDir = this.resolvePath(this.distDir)
this.packagePath = this.resolvePath('package.json')

// Initialize
this.init()
}

init() {
// Try to read package.json if not provided
this._readPackage()

// Init logger
this.logger = consola.withScope(this.packageObj.name)

// Try to load package.js
this._loadPackageJS()
}

resolvePath(...args) {
return resolve(this.rootDir, ...args)
}

_readPackage() {
this.packageObj = readJSONSync(this.packagePath)
}

_loadPackageJS() {
const packageJS = this.resolvePath(this.rootDir, 'package.js')
if (existsSync(packageJS)) {
let fn = require(packageJS)
fn = fn.default || fn
if (typeof fn === 'function') {
fn(this, {
load: (relativeRootDir, opts) => new Package(Object.assign({
rootDir: resolve(this.rootDir, relativeRootDir)
}, opts))
})
}
}
}

writePackage() {
consola.debug('Writing', this.packagePath)
writeFileSync(this.packagePath, JSON.stringify(this.packageObj, null, 2) + '\n')
}

generateVersion() {
const date = Math.round(Date.now() / (1000 * 60))
const gitCommit = this.gitShortCommit()
const baseVersion = this.packageObj.version.split('-')[0]
this.packageObj.version = `${baseVersion}-${date}.${gitCommit}`
}

convertToEdge() {
this.logger.info('Converting to edge package')
this.addNameSuffix('-edge')
this.generateVersion()
this.writePackage()
}

addNameSuffix(suffix) {
if (!this.packageObj.name.includes(suffix)) {
this.packageObj.name += suffix
}
}

build() {
this.emit('build:before')

if (this.edge) {
this.convertToEdge()
}

this.logger.info('Cleaning up')
removeSync(this.distDir)

this.logger.info('Building')
this.exec('rollup', '-c')

this.emit('build:done')
}

publish(tag = 'latest') {
this.logger.info(`publishing ${this.packageObj.name}@${this.packageObj.version} with tag ${tag}`)
this.exec('npm', `publish --tag ${tag}`)
}

copyFieldsFrom(source, fields = []) {
for (const field of fields) {
this.packageObj[field] = source.packageObj[field]
}
}

copyFilesFrom(source, files) {
if (!files) {
files = source.packageObj.files || []
}

for (const file of files) {
const src = resolve(source.rootDir, file)
const dst = resolve(this.rootDir, file)
copySync(src, dst)
}
}

updateDependencies({ dist, sources = [], extras = [], exclude = [] }) {
const dependencies = {}
const requireRegex = /require\('([-@/\w]+)'\)/g

// Extras
for (const name of extras) {
dependencies[name] = null
}

// Scan require() calls inside dist
const distSource = readFileSync(resolve(this.rootDir, dist))

let match = requireRegex.exec(distSource)
while (match) {
const name = match[1]
dependencies[name] = null
match = requireRegex.exec(distSource)
}

// Exclude
for (const name of exclude) {
delete dependencies[name]
}

const builtins = builtinsMap()
// Resolve dependency versions
for (const name in dependencies) {
// Ignore builtin modules
if (builtins[name]) {
delete dependencies[name]
continue
}
// Try sources
for (const source of sources) {
const sourceDeps = source.packageObj.dependencies
if (sourceDeps && sourceDeps[name]) {
dependencies[name] = sourceDeps[name]
break
}
}
// Try to require package.json of dependency
if (dependencies[name] === null) {
try {
const _pkg = require(`${name}/package.json`)
if (!_pkg.version) {
throw Error('No version specified')
}
dependencies[name] = `^${_pkg.version}`
} catch (e) {
consola.warn(e)
delete dependencies[name]
}
}
}

this.packageObj.dependencies = dependencies
}

exec(command, args, silent = false) {
const r = spawnSync(command, args.split(' '), { cwd: this.rootDir }, { env: process.env })

if (!silent) {
const fullCommand = command + ' ' + args
if (r.error) {
this.logger.error(fullCommand, r.error)
} else {
this.logger.success(fullCommand, r.output.join('\n'))
}
}

return {
error: r.error,
pid: r.pid,
status: r.status,
signal: r.signal,
output: (r.output || []).join('\n'),
stdout: String(r.stdout).trim(),
stderr: String(r.stderr).trim()
}
}

gitShortCommit() {
return this.exec('git', 'rev-parse --short HEAD', true).stdout
}

gitBranch() {
return this.exec('git', 'rev-parse --abbrev-ref HEAD', true).stdout
}
}
48 changes: 48 additions & 0 deletions build/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import path from 'path'
import { readJSONSync } from 'fs-extra'
import json from 'rollup-plugin-json'
import commonjs from 'rollup-plugin-commonjs'
import license from 'rollup-plugin-license'
import defaultsDeep from 'lodash/defaultsDeep'
import builtins from './builtins'

export default function rollupConfigFactory({
rootDir = process.cwd(),
plugins = [],
input = 'src/index.js',
...options
}) {
const pkg = readJSONSync(path.resolve(rootDir, 'package.json'))

return defaultsDeep({}, options, {
input: path.resolve(rootDir, input),
output: {
file: path.resolve(rootDir, 'dist', `${pkg.name.replace('-edge', '')}.js`),
format: 'cjs',
sourcemap: true
},
external: [
// Dependencies that will be installed alongise with the nuxt package
...Object.keys(pkg.dependencies || {}),
// Builtin node modules
...builtins,
// Dependencies of nuxt-legacy
'@babel/polyfill'
],
plugins: [
commonjs(),
json(),
license({
banner: [
`/*!`,
` * ${pkg.name} v${pkg.version} (c) 2016-${new Date().getFullYear()}`,
`${pkg.contributors.map(c => ` * - ${c.name}`).join('\n')}`,
` * - All the amazing contributors`,
` * Released under the MIT License.`,
` * Website: https://nuxtjs.org`,
`*/`
].join('\n')
})
].concat(plugins)
})
}
11 changes: 3 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@

const fs = require('fs')
const path = require('path')
const semver = require('semver')

const { engines } = require('./package.json')

if (!semver.satisfies(process.version, engines.node)) {
// Auto fallback to legacy build on older node versions
module.exports = require('./dist/nuxt-legacy.js')
} else if (fs.existsSync(path.resolve(__dirname, '.babelrc'))) {
if (fs.existsSync(path.resolve(__dirname, '.babelrc'))) {
// Use esm version when using linked repository to prevent builds
module.exports = require('./lib/index.js')
const requireModule = require('esm')(module, {})
module.exports = requireModule('./lib/index.js').default
} else {
// Use production bundle by default
module.exports = require('./dist/nuxt.js')
Expand Down
7 changes: 5 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
const requireModule = require('esm')(module, {})
import core from './core'
import builder from './builder'
import * as Utils from './common/utils'
import Options from './common/options'

module.exports = requireModule('./nuxt').default
export default Object.assign({ Utils, Options }, core, builder)
4 changes: 0 additions & 4 deletions lib/nuxt-start.js

This file was deleted.

6 changes: 0 additions & 6 deletions lib/nuxt.js

This file was deleted.

10 changes: 2 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,10 @@
"nuxt": "./bin/nuxt"
},
"scripts": {
"build": "yarn build:nuxt && yarn build:nuxt-start && yarn build:nuxt-legacy",
"build:nuxt": "cross-env NODE_ENV=production rollup -c scripts/rollup/nuxt.js",
"build:nuxt-legacy": "cross-env NODE_ENV=production rollup -c scripts/rollup/nuxt-legacy.js",
"build:nuxt-start": "cross-env NODE_ENV=production rollup -c scripts/rollup/nuxt-start.js",
"build:make-start": "node scripts/make-start",
"clean": "rimraf dist",
"build": "node -r esm ./build/build.js",
"coverage": "codecov",
"lint": "eslint --ext .js,.mjs,.vue bin/** scripts/** lib test examples benchmarks",
"lint": "eslint --ext .js,.mjs,.vue bin/** benchmarks build examples lib packages test",
"postinstall": "opencollective postinstall || exit 0",
"prebuild": "yarn clean",
"security": "nsp check || true",
"test": "yarn test:fixtures && yarn test:unit",
"test:fixtures": "jest test/fixtures",
Expand Down
4 changes: 4 additions & 0 deletions packages/nuxt-legacy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
lib
bin
dist
LICENSE.md
3 changes: 3 additions & 0 deletions packages/nuxt-legacy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# nuxt-legacy

> Legacy build of Nuxt.js for Node.js < 8.0.0

0 comments on commit f854653

Please sign in to comment.