1 | const fs = require('fs')
|
2 | const path = require('path')
|
3 | const chalk = require('chalk')
|
4 | const tildify = require('tildify')
|
5 | const AppError = require('./app-error')
|
6 |
|
7 | exports.cwd = function (cwd, ...args) {
|
8 | return path.resolve(cwd || process.cwd(), ...args)
|
9 | }
|
10 |
|
11 | exports.ownDir = function (...args) {
|
12 | return path.join(__dirname, '../', ...args)
|
13 | }
|
14 |
|
15 | exports.getPublicPath = function (mode, homepage) {
|
16 | if (mode === 'production' && homepage) {
|
17 | return /\/$/.test(homepage) ? homepage : (homepage + '/')
|
18 | }
|
19 | return '/'
|
20 | }
|
21 |
|
22 | let projectPkgCache
|
23 |
|
24 | exports.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 |
|
36 | exports.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 |
|
57 | exports.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 |
|
66 | exports.inferProductionValue = function (value, mode) {
|
67 | if (typeof value !== 'undefined') {
|
68 | return value
|
69 | }
|
70 | return mode === 'production'
|
71 | }
|
72 |
|
73 | exports.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 |
|
84 | exports.stringifyObject = function (obj) {
|
85 | return Object.keys(obj).reduce((curr, next) => {
|
86 | curr[next] = JSON.stringify(obj[next])
|
87 | return curr
|
88 | }, {})
|
89 | }
|