-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathWebpack.scala
More file actions
290 lines (267 loc) · 10.4 KB
/
Copy pathWebpack.scala
File metadata and controls
290 lines (267 loc) · 10.4 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package scalajsbundler
import sbt._
import scalajsbundler.util.{Commands, JS}
import java.io.InputStream
import play.api.libs.json._
import Stats._
import scala.util.{Failure, Success, Try}
object Webpack {
// Represents webpack 5 modes
sealed trait WebpackMode {
def mode: String
}
case object DevelopmentMode extends WebpackMode {
val mode = "development"
}
case object ProductionMode extends WebpackMode {
val mode = "production"
}
object WebpackMode {
def fromBooleanProductionMode(productionMode: Boolean): WebpackMode =
if (productionMode) ProductionMode
else DevelopmentMode
}
/**
* Copies the custom webpack configuration file and the webpackResources to the target dir
*
* @param targetDir target directory
* @param webpackResources Resources to copy
* @param customConfigFile User supplied config file
* @return The copied config file.
*/
def copyCustomWebpackConfigFiles(targetDir: File, webpackResources: Seq[File])(customConfigFile: File): File = {
def copyToWorkingDir(targetDir: File)(file: File): File = {
val copy = targetDir / file.name
IO.copyFile(file, copy)
copy
}
webpackResources.foreach(copyToWorkingDir(targetDir))
copyToWorkingDir(targetDir)(customConfigFile)
}
/**
* Writes the webpack configuration file. The output file is designed to be minimal, and to be extended,
* however, the `entry` and `output` keys must be preserved in order for the bundler to work as expected.
*
* @param emitSourceMaps Whether source maps is enabled at all
* @param entry The input entrypoint file to process via webpack
* @param webpackConfigFile webpack configuration file to write to
* @param libraryBundleName If defined, generate a library bundle named `libraryBundleName`
* @param log Logger
*/
def writeConfigFile(
emitSourceMaps: Boolean,
entry: BundlerFile.WebpackInput,
webpackConfigFile: BundlerFile.WebpackConfig,
libraryBundleName: Option[String],
mode: WebpackMode,
devServerPort: Int,
log: Logger
): Unit = {
val webpackConfigContent = generateConfigFile(emitSourceMaps, entry, webpackConfigFile, libraryBundleName, mode,
devServerPort)
log.info("Writing scalajs.webpack.config.js")
IO.write(webpackConfigFile.file, webpackConfigContent.show)
}
private def generateConfigFile(
emitSourceMaps: Boolean,
entry: BundlerFile.WebpackInput,
webpackConfigFile: BundlerFile.WebpackConfig,
libraryBundleName: Option[String],
mode: WebpackMode,
devServerPort: Int
): JS = {
val webpackNpmPackage = NpmPackage.getForModule(webpackConfigFile.targetDir.toFile, "webpack")
webpackNpmPackage.flatMap(_.major) match {
case Some(5) =>
// Build the output configuration, configured for library output
// if a library bundle name is provided
val output = libraryBundleName match {
case Some(bundleName) =>
JS.obj(
"path" -> JS.str(webpackConfigFile.targetDir.toAbsolutePath.toString),
"filename" -> JS.str(BundlerFile.Library.fileName("[name]")),
"library" -> JS.str(bundleName),
"libraryTarget" -> JS.str("var")
)
case None =>
JS.obj(
"path" -> JS.str(webpackConfigFile.targetDir.toAbsolutePath.toString),
"filename" -> JS.str(BundlerFile.ApplicationBundle.fileName("[name]"))
)
}
JS.ref("module").dot("exports").assign(JS.obj(Seq(
"entry" -> JS.obj(
entry.project -> JS.arr(JS.str(entry.file.absolutePath))
),
"output" -> output,
"mode" -> JS.str(mode.mode),
"devServer" -> JS.obj("port" -> JS.int(devServerPort)),
) ++ (
if (emitSourceMaps) {
Seq(
"devtool" -> JS.str("source-map"),
"module" -> JS.obj(
"rules" -> JS.arr(
JS.obj(
"test" -> JS.regex("\\.js$"),
"enforce" -> JS.str("pre"),
"use" -> JS.arr(JS.str("source-map-loader"))
)
)
)
)
} else Nil
): _*))
case Some(x) =>
sys.error(s"Unsupported webpack major version $x")
case None =>
sys.error("No webpack version defined")
}
}
/**
* Run webpack to bundle the application.
*
* @param emitSourceMaps Whether or not source maps are enabled
* @param generatedWebpackConfigFile Webpack config file generated by scalajs-bundler
* @param customWebpackConfigFile User supplied config file
* @param webpackResources Additional resources to be copied to the working folder
* @param entry Scala.js application to bundle
* @param targetDir Target directory (and working directory for Nodejs)
* @param extraArgs Extra arguments passed to webpack
* @param mode Mode for webpack 5
* @param devServerPort Port used by webpack-dev-server
* @param log Logger
* @return The generated bundles
*/
def bundle(
emitSourceMaps: Boolean,
generatedWebpackConfigFile: BundlerFile.WebpackConfig,
customWebpackConfigFile: Option[File],
webpackResources: Seq[File],
entry: BundlerFile.Application,
targetDir: File,
extraArgs: Seq[String],
nodeArgs: Seq[String],
mode: WebpackMode,
devServerPort: Int,
log: Logger
): BundlerFile.ApplicationBundle = {
writeConfigFile(emitSourceMaps, entry, generatedWebpackConfigFile, None, mode, devServerPort, log)
val configFile = customWebpackConfigFile
.map(Webpack.copyCustomWebpackConfigFiles(targetDir, webpackResources))
.getOrElse(generatedWebpackConfigFile.file)
log.info("Bundling the application with its NPM dependencies")
val args = extraArgs ++: Seq("--config", configFile.absolutePath)
val stats = Webpack.run(nodeArgs: _*)(args: _*)(targetDir, log)
stats.foreach(_.print(log))
// Attempt to discover the actual name produced by webpack indexing by chunk name and discarding maps
val bundle = generatedWebpackConfigFile.asApplicationBundle(stats)
assert(bundle.file.exists(), "Webpack failed to create application bundle")
assert(bundle.assets.forall(_.exists()), "Webpack failed to create application assets")
bundle
}
/**
* Run webpack to bundle the application.
*
* @param emitSourceMaps Are source maps enabled?
* @param generatedWebpackConfigFile Webpack config file generated by scalajs-bundler
* @param customWebpackConfigFile User supplied config file
* @param webpackResources Additional webpack resources to include in the working directory
* @param entryPointFile The entrypoint file to bundle dependencies for
* @param libraryModuleName The library module name to assign the webpack bundle to
* @param extraArgs Extra arguments passed to webpack
* @param mode Mode for webpack 5
* @param log Logger
* @return The generated bundle
*/
def bundleLibraries(
emitSourceMaps: Boolean,
generatedWebpackConfigFile: BundlerFile.WebpackConfig,
customWebpackConfigFile: Option[File],
webpackResources: Seq[File],
entryPointFile: BundlerFile.EntryPoint,
libraryModuleName: String,
extraArgs: Seq[String],
nodeArgs: Seq[String],
mode: WebpackMode,
devServerPort: Int,
log: Logger
): BundlerFile.Library = {
writeConfigFile(
emitSourceMaps,
entryPointFile,
generatedWebpackConfigFile,
Some(libraryModuleName),
mode,
devServerPort,
log
)
val configFile = customWebpackConfigFile
.map(Webpack.copyCustomWebpackConfigFiles(generatedWebpackConfigFile.targetDir.toFile, webpackResources))
.getOrElse(generatedWebpackConfigFile.file)
val args = extraArgs ++: Seq("--config", configFile.absolutePath)
val stats = Webpack.run(nodeArgs: _*)(args: _*)(generatedWebpackConfigFile.targetDir.toFile, log)
stats.foreach(_.print(log))
val library = generatedWebpackConfigFile.asLibrary(stats)
assert(library.file.exists, "Webpack failed to create library file")
assert(library.assets.forall(_.exists), "Webpack failed to create library assets")
library
}
private def jsonOutput(cmd: Seq[String], logger: Logger)(in: InputStream): Option[WebpackStats] = {
Try {
val parsed = Json.parse(in)
val p = parsed.as[WebpackStats]
if (p.warnings.nonEmpty || p.errors.nonEmpty) {
logger.info("")
// Filtering is a workaround for #111
p.warnings.filterNot(_.message.contains("https://raw.githubusercontent.com")).foreach { warning =>
warning.moduleName match {
case Some(moduleName) =>
logger.warn(s"WARNING in $moduleName")
case None =>
logger.warn("WARNING")
}
logger.warn(warning.message)
logger.warn("\n")
}
p.errors.foreach { error =>
error.moduleName match {
case Some(moduleName) =>
logger.error(s"ERROR in $moduleName ${error.loc.getOrElse("")}")
case None =>
logger.error("ERROR")
}
logger.error(error.message)
logger.error("\n")
}
}
p
} match {
case Success(x) =>
Some(x)
case Failure(e) =>
// In some cases errors are not reported on the json output but comes on stdout
// where they cannot be parsed as json. The best we can do here is to suggest
// running the command manually
logger.error(s"Failure on parsing the output of webpack: ${e.getMessage}")
logger.error(s"You can try to manually execute the command")
logger.error(cmd.mkString(" "))
logger.error("\n")
None
}
}
/**
* Runs the webpack command.
*
* @param nodeArgs node.js cli flags
* @param args Arguments to pass to the webpack command
* @param workingDir Working directory in which the Nodejs will be run (where there is the `node_modules` subdirectory)
* @param log Logger
*/
def run(nodeArgs: String*)(args: String*)(workingDir: File, log: Logger): Option[WebpackStats] = {
val webpackBin = workingDir / "node_modules" / "webpack" / "bin" / "webpack"
val params = nodeArgs ++ Seq(webpackBin.absolutePath, "--profile", "--json") ++ args
val cmd = "node" +: params
Commands.run(cmd, workingDir, log, jsonOutput(cmd, log)).fold(sys.error, _.flatten)
}
}