This repository has been archived by the owner on Jun 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
164 lines (138 loc) 路 5.19 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
const chalk = require('chalk')
const fs = require('fs')
const mime = require('mime-types')
const ms = require('ms')
const { Nuxt, Builder, Generator } = require('nuxt')
const path = require('path')
const { traverse } = require('./utils/traverse')
let BundleBuilder
try {
BundleBuilder = require('@nuxt/webpack').BundleBuilder
} catch (e) {
//
}
function normlizeConfig(config) {
return {
version: config.version,
bucketName: config.bucketName,
assetsPath: config.assetsPath || '.nuxt/dist/client',
cdnPath: config.cdnPath || null,
assetsCacheMaxAge: `${config.assetsCacheMaxAge || '365d'}`,
acl: config.acl || 'public-read',
}
}
class ServerlessNuxtPlugin {
constructor(serverless, options) {
this.serverless = serverless
this.options = options || {}
this.servicePath = this.serverless.service.serverless.config.servicePath
this.isUploadedAssets = false
this.commands = {
nuxt: {
usage: 'Build Nuxt and upload assets files.',
lifecycleEvents: ['build', 'upload'],
commands: {
build: {
usage: 'Build Nuxt.',
lifecycleEvents: ['build'],
},
upload: {
usage: 'Upload asset files.',
lifecycleEvents: ['upload'],
},
},
},
}
this.hooks = {
'before:package:createDeploymentArtifacts': this.build.bind(this),
'after:aws:deploy:deploy:uploadArtifacts': this.afterUploadArtifacts.bind(this),
'after:aws:deploy:deploy:updateStack': this.afterUpdateStack.bind(this),
'nuxt:build': this.build.bind(this),
'nuxt:upload': this.upload.bind(this),
}
}
async build() {
const config = normlizeConfig(this.serverless.service.custom.nuxt || {})
const servicePath = this.serverless.service.serverless.config.servicePath
const configPath = path.resolve(servicePath, 'nuxt.config')
const assetBasePath = config.cdnPath ? config.cdnPath.replace(/\/+$/, '') : `https://${config.bucketName}.s3.amazonaws.com`
this.serverless.service.provider.environment = Object.assign(this.serverless.service.provider.environment || {}, {
SERVERLESS_NUXT_PUBLIC_PATH: `${assetBasePath}/${config.version}/`,
})
const env = this.serverless.service.provider.environment || {}
Object.assign(process.env, env)
if (process.env.SERVERLESS_NUXT_SKIP_BUILD) {
this.serverless.cli.consoleLog(`Serverless Nuxt Plugin: ${chalk.yellow('build nuxt')} ${chalk.green('skip!')}`)
return
}
this.serverless.cli.consoleLog(`Serverless Nuxt Plugin: ${chalk.yellow('build nuxt')}`)
let nuxtConfig = require(configPath) // eslint-disable-line
nuxtConfig = nuxtConfig.default ? nuxtConfig.default : nuxtConfig
const nuxt = new Nuxt({
...nuxtConfig,
server: false,
dev: false,
_build: true,
})
if (nuxt.ready) {
await nuxt.ready()
}
const builder = new Builder(nuxt, BundleBuilder)
if (typeof builder.build === 'function') { // for nuxt v2.9.x
await builder.build()
} else {
const generator = new Generator(nuxt, builder)
await generator.generate({ build: true })
}
}
async afterUploadArtifacts() {
this.serverless.cli.consoleLog(`Serverless Nuxt Plugin: ${chalk.yellow('after upload artifacts')}`)
await this.upload(true)
}
async afterUpdateStack() {
this.serverless.cli.consoleLog(`Serverless Nuxt Plugin: ${chalk.yellow('after update stack')}`)
if (!this.isUploadedAssets) {
await this.upload()
}
}
async upload(ignoreBucketExists = false) {
const provider = this.serverless.getProvider('aws')
const awsCredentials = provider.getCredentials()
const s3 = new provider.sdk.S3({
region: provider.getRegion(),
credentials: awsCredentials.credentials,
})
const config = normlizeConfig(this.serverless.service.custom.nuxt || {})
try {
await s3.headBucket({
Bucket: config.bucketName,
}).promise()
} catch (e) {
if (ignoreBucketExists) {
this.serverless.cli.consoleLog(`Serverless Nuxt Plugin: ${chalk.yellow('not found asset bucket')}`)
return
}
throw new Error('not found asset bucket')
}
const servicePath = this.serverless.service.serverless.config.servicePath
const assetsPath = path.resolve(servicePath, config.assetsPath)
this.serverless.cli.consoleLog(`Serverless Nuxt Plugin: ${chalk.yellow('upload asset files')}`)
const assetsFiles = await traverse(assetsPath)
await Promise.all(assetsFiles.map((file) => {
const fileTargetPath = [config.version, file.replace(assetsPath, '')].join('/')
.replace(/\\/g, '/') // for window path separator #311
.replace(/^\/+|\/+$/, '')
.replace(/\/+/g, '/')
return s3.putObject({
Bucket: config.bucketName,
Key: fileTargetPath,
Body: fs.readFileSync(file),
ACL: config.acl,
ContentType: mime.lookup(file) || null,
CacheControl: `public, max-age=${Math.floor(ms(config.assetsCacheMaxAge) / 1000)}`, // let the browser cache all static files for 1 year since they receive a unique hash by Nuxt
}).promise()
}))
this.isUploadedAssets = true
}
}
module.exports = ServerlessNuxtPlugin