UNPKG

2.42 kBJavaScriptView Raw
1const fs = require('fs')
2const path = require('path')
3const chalk = require('chalk')
4const tildify = require('tildify')
5const AppError = require('./app-error')
6
7exports.cwd = function (cwd, ...args) {
8 return path.resolve(cwd || process.cwd(), ...args)
9}
10
11exports.ownDir = function (...args) {
12 return path.join(__dirname, '../', ...args)
13}
14
15exports.getPublicPath = function (mode, homepage) {
16 if (mode === 'production' && homepage) {
17 return /\/$/.test(homepage) ? homepage : (homepage + '/')
18 }
19 return '/'
20}
21
22let projectPkgCache
23
24exports.readPkg = function () {
25 try {
26 projectPkgCache = projectPkgCache || require(exports.cwd('package.json'))
27 return projectPkgCache
28 } catch (err) {
29 if (err.code === 'MODULE_NOT_FOUND') {
30 return {}
31 }
32 throw new AppError(err.message)
33 }
34}
35
36exports.inferHTML = function (options) {
37 const result = {
38 title: 'Poi App',
39 template: exports.ownDir('lib/index.ejs')
40 }
41
42 const pkg = exports.readPkg()
43 result.pkg = pkg
44 result.title = pkg.productName || pkg.name
45 result.description = pkg.description
46
47 const templatePath = path.resolve(options.cwd || process.cwd(), 'index.ejs')
48 if (fs.existsSync(templatePath)) {
49 console.log(`> Using external HTML template file`)
50 console.log(chalk.dim(`> location: "${tildify(templatePath)}"`))
51 result.template = templatePath
52 }
53
54 return result
55}
56
57exports.getFileNames = function (useHash, customFileName) {
58 return Object.assign({
59 js: useHash ? '[name].[chunkhash:8].js' : '[name].js',
60 css: useHash ? '[name].[contenthash:8].css' : '[name].css',
61 static: useHash ? 'static/media/[name].[hash:8].[ext]' : 'static/media/[name].[ext]',
62 chunk: useHash ? '[name].[chunkhash:8].chunk.js' : '[name].chunk.js'
63 }, customFileName)
64}
65
66exports.inferProductionValue = function (value, mode) {
67 if (typeof value !== 'undefined') {
68 return value
69 }
70 return mode === 'production'
71}
72
73exports.promisify = function (fn) {
74 return (...args) => {
75 return new Promise((resolve, reject) => {
76 fn(...args, (err, result) => {
77 if (err) return reject(err)
78 resolve(result)
79 })
80 })
81 }
82}
83
84exports.stringifyObject = function (obj) {
85 return Object.keys(obj).reduce((curr, next) => {
86 curr[next] = JSON.stringify(obj[next])
87 return curr
88 }, {})
89}
90
91exports.createSet = function (value) {
92 return Array.isArray(value) ? new Set(value) : new Set([value])
93}