UNPKG

2.73 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 images: 'assets/images/[name].[hash:8].[ext]',
62 fonts: useHash ? 'assets/fonts/[name].[hash:8].[ext]' : 'assets/fonts/[name].[ext]',
63 chunk: useHash ? '[name].[chunkhash:8].chunk.js' : '[name].chunk.js'
64 }, customFileName)
65}
66
67exports.inferProductionValue = function (value, mode) {
68 if (typeof value !== 'undefined') {
69 return value
70 }
71 return mode === 'production'
72}
73
74exports.promisify = function (fn) {
75 return (...args) => {
76 return new Promise((resolve, reject) => {
77 fn(...args, (err, result) => {
78 if (err) return reject(err)
79 resolve(result)
80 })
81 })
82 }
83}
84
85exports.stringifyObject = function (obj) {
86 return Object.keys(obj).reduce((curr, next) => {
87 curr[next] = JSON.stringify(obj[next])
88 return curr
89 }, {})
90}
91
92exports.createSet = function (value) {
93 return Array.isArray(value) ? new Set(value) : new Set([value])
94}
95
96exports.unspecifiedAddress = function (host) {
97 return host === '0.0.0.0' || host === '::'
98}
99
100exports.getFullEnvString = function (env) {
101 return Object.keys(env).reduce((res, key) => {
102 res[`process.env.${key}`] = env[key]
103 return res
104 }, {})
105}