Unverified Commit 58f5dd29 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add Typescript types for builds functions (#5791)

parent a9cf735f
...@@ -13,14 +13,15 @@ ...@@ -13,14 +13,15 @@
"pretest": "npm run lint", "pretest": "npm run lint",
"test": "npm run testall || npm run testall", "test": "npm run testall || npm run testall",
"coveralls": "cat ./test/coverage/lcov.info | coveralls", "coveralls": "cat ./test/coverage/lcov.info | coveralls",
"lint": "standard", "lint": "standard && standard --parser typescript-eslint-parser --plugin typescript packages/**/*.ts",
"prepublish": "lerna run prepublish", "prepublish": "lerna run prepublish",
"publish-canary": "lerna version prerelease --preid canary --force-publish", "publish-canary": "lerna version prerelease --preid canary --force-publish",
"lint-staged": "lint-staged" "lint-staged": "lint-staged"
}, },
"pre-commit": "lint-staged", "pre-commit": "lint-staged",
"lint-staged": { "lint-staged": {
"*.js": "standard", "*.js": "standard --fix",
"*.ts": "standard --parser typescript-eslint-parser --plugin typescript --fix",
"packages/**/bin/*": "standard" "packages/**/bin/*": "standard"
}, },
"standard": { "standard": {
...@@ -48,6 +49,7 @@ ...@@ -48,6 +49,7 @@
"chromedriver": "2.42.0", "chromedriver": "2.42.0",
"clone": "2.1.1", "clone": "2.1.1",
"coveralls": "3.0.2", "coveralls": "3.0.2",
"eslint-plugin-typescript": "0.14.0",
"express": "4.16.3", "express": "4.16.3",
"fkill": "5.1.0", "fkill": "5.1.0",
"flatten": "1.0.2", "flatten": "1.0.2",
...@@ -66,6 +68,7 @@ ...@@ -66,6 +68,7 @@
"rimraf": "2.6.2", "rimraf": "2.6.2",
"standard": "11.0.1", "standard": "11.0.1",
"taskr": "1.1.0", "taskr": "1.1.0",
"typescript-eslint-parser": "21.0.1",
"wait-port": "0.2.2", "wait-port": "0.2.2",
"wd": "1.10.3", "wd": "1.10.3",
"webpack-bundle-analyzer": "3.0.3" "webpack-bundle-analyzer": "3.0.3"
......
module.exports = require('./dist/server/config') module.exports = require('./dist/server/config').default
...@@ -14,7 +14,7 @@ const argv = parseArgs(process.argv.slice(2), { ...@@ -14,7 +14,7 @@ const argv = parseArgs(process.argv.slice(2), {
}) })
if (argv.help) { if (argv.help) {
console.log(` printAndExit(`
Description Description
Compiles the application for production deployment Compiles the application for production deployment
...@@ -24,8 +24,7 @@ if (argv.help) { ...@@ -24,8 +24,7 @@ if (argv.help) {
<dir> represents where the compiled dist folder should go. <dir> represents where the compiled dist folder should go.
If no directory is provided, the dist folder will be created in the current directory. If no directory is provided, the dist folder will be created in the current directory.
You can set a custom folder in config https://github.com/zeit/next.js#custom-configuration, otherwise it will be created inside '.next' You can set a custom folder in config https://github.com/zeit/next.js#custom-configuration, otherwise it will be created inside '.next'
`) `, 0)
process.exit(0)
} }
const dir = resolve(argv._[0] || '.') const dir = resolve(argv._[0] || '.')
...@@ -46,5 +45,6 @@ if (!existsSync(join(dir, 'pages'))) { ...@@ -46,5 +45,6 @@ if (!existsSync(join(dir, 'pages'))) {
build(dir, null, lambdas) build(dir, null, lambdas)
.catch((err) => { .catch((err) => {
console.error('> Build error occured')
printAndExit(err) printAndExit(err)
}) })
...@@ -43,7 +43,7 @@ export default function ({ types: t }: {types: typeof BabelTypes}): PluginObj { ...@@ -43,7 +43,7 @@ export default function ({ types: t }: {types: typeof BabelTypes}): PluginObj {
const bindingName = defaultSpecifier.node.local.name const bindingName = defaultSpecifier.node.local.name
const binding = path.scope.getBinding(bindingName) const binding = path.scope.getBinding(bindingName)
if(!binding) { if (!binding) {
return return
} }
...@@ -106,7 +106,7 @@ export default function ({ types: t }: {types: typeof BabelTypes}): PluginObj { ...@@ -106,7 +106,7 @@ export default function ({ types: t }: {types: typeof BabelTypes}): PluginObj {
loader = propertiesMap.modules.get('value') loader = propertiesMap.modules.get('value')
} }
if(!loader || Array.isArray(loader)) { if (!loader || Array.isArray(loader)) {
return return
} }
const dynamicImports: BabelTypes.StringLiteral[] = [] const dynamicImports: BabelTypes.StringLiteral[] = []
...@@ -114,14 +114,14 @@ export default function ({ types: t }: {types: typeof BabelTypes}): PluginObj { ...@@ -114,14 +114,14 @@ export default function ({ types: t }: {types: typeof BabelTypes}): PluginObj {
loader.traverse({ loader.traverse({
Import (path) { Import (path) {
const args = path.parentPath.get('arguments') const args = path.parentPath.get('arguments')
if(!Array.isArray(args)) return if (!Array.isArray(args)) return
const node: any = args[0].node const node: any = args[0].node
dynamicImports.push(node) dynamicImports.push(node)
} }
}) })
if (!dynamicImports.length) return if (!dynamicImports.length) return
options.node.properties.push(t.objectProperty( options.node.properties.push(t.objectProperty(
t.identifier('loadableGenerated'), t.identifier('loadableGenerated'),
t.objectExpression([ t.objectExpression([
......
import webpack from 'webpack'
type CompilerResult = {
errors: Error[],
warnings: Error[]
}
export function runCompiler (config: webpack.Configuration[]): Promise<CompilerResult> {
return new Promise(async (resolve, reject) => {
const compiler = webpack(config)
compiler.run((err, multiStats: any) => {
if (err) {
return reject(err)
}
const result: CompilerResult = multiStats.stats.reduce((result: CompilerResult, stat: webpack.Stats): CompilerResult => {
if (stat.compilation.errors.length > 0) {
result.errors.push(...stat.compilation.errors)
}
if (stat.compilation.warnings.length > 0) {
result.warnings.push(...stat.compilation.warnings)
}
return result
}, {errors: [], warnings: []})
resolve(result)
})
})
}
import { join } from 'path'
import promisify from '../lib/promisify'
import fs from 'fs'
import webpack from 'webpack'
import nanoid from 'nanoid'
import loadConfig from 'next-server/next-config'
import { PHASE_PRODUCTION_BUILD, BUILD_ID_FILE } from 'next-server/constants'
import getBaseWebpackConfig from './webpack'
import {generateBuildId} from './generate-build-id'
const access = promisify(fs.access)
const writeFile = promisify(fs.writeFile)
async function ensureProjectDirectoryIsWriteAble (dir) {
try {
await access(dir, (fs.constants || fs).W_OK)
} catch (err) {
throw new Error('Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable')
}
}
export default async function build (dir, conf = null, lambdas = false) {
const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const lambdasOption = config.lambdas ? config.lambdas : lambdas
const distDir = join(dir, config.distDir)
const buildId = await generateBuildId(config.generateBuildId, nanoid)
await ensureProjectDirectoryIsWriteAble(dir)
try {
const configs = await Promise.all([
getBaseWebpackConfig(dir, { buildId, isServer: false, config, lambdas: lambdasOption }),
getBaseWebpackConfig(dir, { buildId, isServer: true, config, lambdas: lambdasOption })
])
await runCompiler(configs)
await writeBuildId(distDir, buildId)
} catch (err) {
console.error(`> Failed to build`)
throw err
}
}
function runCompiler (compiler) {
return new Promise(async (resolve, reject) => {
const webpackCompiler = await webpack(await compiler)
webpackCompiler.run((err, stats) => {
if (err) {
console.log({...err})
console.log(...stats.errors)
return reject(err)
}
let buildFailed = false
for (const stat of stats.stats) {
for (const error of stat.compilation.errors) {
buildFailed = true
console.error('ERROR', error)
console.error('ORIGINAL ERROR', error.error)
}
for (const warning of stat.compilation.warnings) {
console.warn('WARNING', warning)
}
}
if (buildFailed) {
return reject(new Error('Webpack errors'))
}
resolve()
})
})
}
async function writeBuildId (distDir, buildId) {
const buildIdPath = join(distDir, BUILD_ID_FILE)
await writeFile(buildIdPath, buildId, 'utf8')
}
import { join } from 'path'
import nanoid from 'nanoid'
import loadConfig from 'next-server/next-config'
import { PHASE_PRODUCTION_BUILD } from 'next-server/constants'
import getBaseWebpackConfig from './webpack-config'
import {generateBuildId} from './generate-build-id'
import {writeBuildId} from './write-build-id'
import {isWriteable} from './is-writeable'
import {runCompiler} from './compiler'
export default async function build (dir: string, conf = null, lambdas: boolean = false): Promise<void> {
if (!await isWriteable(dir)) {
throw new Error('> Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable')
}
const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const lambdasOption = config.lambdas ? config.lambdas : lambdas
const distDir = join(dir, config.distDir)
const buildId = await generateBuildId(config.generateBuildId, nanoid)
const configs: any = await Promise.all([
getBaseWebpackConfig(dir, { buildId, isServer: false, config, lambdas: lambdasOption }),
getBaseWebpackConfig(dir, { buildId, isServer: true, config, lambdas: lambdasOption })
])
const result = await runCompiler(configs)
if (result.warnings.length > 0) {
console.warn('> Emitted warnings from webpack')
console.warn(...result.warnings)
}
if (result.errors.length > 0) {
console.error(...result.errors)
throw new Error('> Build failed because of webpack errors')
}
await writeBuildId(distDir, buildId)
}
import fs from 'fs'
import {promisify} from 'util'
const access = promisify(fs.access)
export async function isWriteable (directory: string): Promise<boolean> {
try {
await access(directory, (fs.constants || fs).W_OK)
return true
} catch (err) {
return false
}
}
import fs from 'fs'
import {promisify} from 'util'
import {join} from 'path'
import {BUILD_ID_FILE} from 'next-server/constants'
const writeFile = promisify(fs.writeFile)
export async function writeBuildId (distDir: string, buildId: string): Promise<void> {
const buildIdPath = join(distDir, BUILD_ID_FILE)
await writeFile(buildIdPath, buildId, 'utf8')
}
...@@ -94,12 +94,13 @@ ...@@ -94,12 +94,13 @@
"@taskr/clear": "1.1.0", "@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0", "@taskr/esnext": "1.1.0",
"@taskr/watch": "1.1.0", "@taskr/watch": "1.1.0",
"@types/babel__core": "7.0.4",
"@types/babel__traverse": "7.0.3",
"@types/nanoid": "1.2.0",
"@types/babel-types": "7.0.4", "@types/babel-types": "7.0.4",
"@types/babel__core": "7.0.4",
"@types/babel__generator": "7.0.1", "@types/babel__generator": "7.0.1",
"@types/babel__template": "7.0.1", "@types/babel__template": "7.0.1",
"@types/babel__traverse": "7.0.3",
"@types/nanoid": "1.2.0",
"@types/webpack": "4.4.20",
"taskr": "1.1.0", "taskr": "1.1.0",
"typescript": "3.1.6" "typescript": "3.1.6"
}, },
......
...@@ -5,7 +5,7 @@ import errorOverlayMiddleware from './lib/error-overlay-middleware' ...@@ -5,7 +5,7 @@ import errorOverlayMiddleware from './lib/error-overlay-middleware'
import del from 'del' import del from 'del'
import onDemandEntryHandler, {normalizePage} from './on-demand-entry-handler' import onDemandEntryHandler, {normalizePage} from './on-demand-entry-handler'
import webpack from 'webpack' import webpack from 'webpack'
import getBaseWebpackConfig from '../build/webpack' import getBaseWebpackConfig from '../build/webpack-config'
import {IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES, CLIENT_STATIC_FILES_PATH} from 'next-server/constants' import {IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES, CLIENT_STATIC_FILES_PATH} from 'next-server/constants'
import {route} from 'next-server/dist/server/router' import {route} from 'next-server/dist/server/router'
import {renderScriptError} from 'next-server/dist/server/render' import {renderScriptError} from 'next-server/dist/server/render'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment