diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a74aa88..6ff6e7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,9 +23,9 @@ jobs: runs-on: ${{ matrix.os.name }} steps: - - uses: actions/checkout@v4 - - uses: coursier/cache-action@v6 - - uses: coursier/setup-action@v1 + - uses: actions/checkout@v7 + - uses: coursier/cache-action@v8 + - uses: coursier/setup-action@v3 with: jvm: temurin:17 @@ -34,7 +34,7 @@ jobs: ${{ matrix.os.command }} --no-server --jobs 0 _.test - name: Publish Test Report - uses: mikepenz/action-junit-report@v5 + uses: mikepenz/action-junit-report@v6 if: always() # always run even if the previous step fails with: detailed_summary: true @@ -47,11 +47,13 @@ jobs: if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v')) steps: - - uses: actions/checkout@v4 - - uses: coursier/cache-action@v6 - - uses: coursier/setup-action@v1 + - uses: actions/checkout@v7 with: - jvm: temurin:11 + fetch-depth: 0 + - uses: coursier/cache-action@v8 + - uses: coursier/setup-action@v3 + with: + jvm: temurin:17 - name: Publish run: ./mill --no-server --jobs 0 mill.scalalib.SonatypeCentralPublishModule/ diff --git a/.mill-version b/.mill-version index 5c3b478..cd82ed0 100644 --- a/.mill-version +++ b/.mill-version @@ -1 +1 @@ -1.0.4-native +1.1.10-native diff --git a/.scalafmt.conf b/.scalafmt.conf index b9f63f4..0ecf3b6 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,2 +1,40 @@ -version = "3.9.7" -runner.dialect = scala213 \ No newline at end of file +version = "3.11.5" +runner.dialect = scala3 +# maxColumn = 120 + +rewrite { + rules = [Imports, SortModifiers, AvoidInfix, RedundantBraces, RedundantParens, PreferCurlyFors] + imports { + expand = true + sort = scalastyle + groups = [ + ["build\\..*"] + ["io.github.nafg.millbundler\\..*", "millbundler\\..*", "nafg.millbundler\\..*"] + ["[a-z0-9]*\\..*"] + ["scala\\..*"] + ["java\\..*"] + ["mill\\..*", "os\\..*"] + ] + } + redundantBraces { + stringInterpolation = true + generalExpressions = true + ifElseExpressions = true + methodBodies = true + } + scala3 { + convertToNewSyntax = true + removeOptionalBraces = yes + insertEndMarkerMinLines = 10 + } +} + +newlines { + source = keep + afterCurlyLambdaParams = squash + beforeCurlyLambdaParams = multilineWithCaseOnly + implicitParamListModifierPrefer = after + topLevelStatementBlankLines = [ + { blanks = 1 } + ] +} diff --git a/README.md b/README.md index 32558b8..dc7125f 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ A Mill plugin for managing NPM dependencies for Scala.js code, and bundling the output. +This repository is the maintained fork of [nafg/mill-bundler](https://github.com/nafg/mill-bundler). Published artifacts use the `io.github.thijsbroersen.millbundler` group id. Scala packages stay `io.github.nafg.millbundler`. + ## Usage ### Managing NPM dependencies @@ -15,12 +17,12 @@ also override the `jsDeps` target. You can see the result by running `mill frontend.allJsDeps`. ```scala -import $ivy.`io.github.nafg.millbundler::jsdeps::0.1.0`, io.github.nafg.millbundler.jsdeps._ +import $ivy.`io.github.thijsbroersen.millbundler::jsdeps_mill1::0.1.0`, io.github.nafg.millbundler.jsdeps._ object frontend extends ScalaJSNpmModule { - override def scalaVersion = "3.7.2" - override def scalaJSVersion = "1.19.0" + override def scalaVersion = "3.8.2" + override def scalaJSVersion = "1.22.0" override def jsDeps = super.jsDeps() ++ JsDeps( @@ -47,7 +49,7 @@ To bundle your Scala.js code, mix in `ScalaJSRollupModule` or `ScalaJSWebpackMod ScalaJSNpmModule, so everything from the previous section applies. ```scala -import $ivy.`io.github.nafg.millbundler::millbundler::0.1.0`, io.github.nafg.millbundler._ +import $ivy.`io.github.thijsbroersen.millbundler::millbundler_mill1::0.1.0`, io.github.nafg.millbundler._ object frontend extends ScalaJSRollupModule { @@ -55,11 +57,36 @@ object frontend extends ScalaJSRollupModule { } ``` -You can then run `mill frontend.devBundle` or `mill frontend.prodBundle` to bundle your Scala.js code into a single -JavaScript file. +You can then run `mill frontend.devBundle` or `mill frontend.prodBundle` to bundle your Scala.js code. + +When the Scala.js linker produces a single public module, bundling writes one output file (`bundleFilename`, default +`out-bundle.js`). When the linker produces multiple public modules, pass all entry files to the bundler automatically +via `getReportMainFilePath`; outputs are written using `outputEntryFileNames` (default `out-bundle-[name].js`), where +`[name]` is derived from each input file name. + +Override `bundleFilename` / `outputEntryFileNames` to customize output naming. For Rollup, `rollupOutputName` sets the +IIFE global name when bundling a single entry. ### Testing `ScalaJSNpmModule`, `ScalaJSRollupModule`, `ScalaJSWebpackModule` provide a `Test` trait in their respective companion objects. You can mix it into your test module to make sure your tests run after the NPM dependencies are installed, and after the bundle is built. + +## Publishing + +Requires Mill 1.1.10 or newer. The plugin is compiled for Mill binary platform `1`, so the artifact ids end in `_mill1`. + +| Module | Ivy coordinate | +| --- | --- | +| jsdeps | `io.github.thijsbroersen.millbundler::jsdeps_mill1::` | +| millbundler | `io.github.thijsbroersen.millbundler::millbundler_mill1::` | + +The version comes from the nearest `v*` git tag (`untaggedSuffix = -SNAPSHOT`). Pushing tag `v0.1.0` to this repository publishes `0.1.0` to Maven Central. + +Before the first release: + +1. Register the `io.github.thijsbroersen` namespace on the [Central Portal](https://central.sonatype.com/). The group `io.github.thijsbroersen.millbundler` is covered by that namespace. +2. Add these GitHub Actions secrets: `MILL_SONATYPE_USERNAME`, `MILL_SONATYPE_PASSWORD`, `MILL_PGP_SECRET_BASE64`, `MILL_PGP_PASSPHRASE`. + +The publish job runs `./mill mill.scalalib.SonatypeCentralPublishModule/` on `v*` tags. It checks out full git history so the tag version resolves. diff --git a/build.mill b/build.mill index 4814735..75316f3 100644 --- a/build.mill +++ b/build.mill @@ -6,16 +6,15 @@ import mill.scalalib.scalafmt.* import mill.util.VcsVersion -trait BaseScalaModule extends ScalaModule { - override def scalaVersion = "3.7.2" +trait BaseScalaModule extends ScalaModule: + override def scalaVersion = "3.8.2" override def zincReportCachedProblems = true -} trait BasePublishModule extends BaseScalaModule with SonatypeCentralPublishModule - with ScalafmtModule { - override def scalaVersion = "3.7.2" + with ScalafmtModule: + override def scalaVersion = "3.8.2" override def publishVersion: T[String] = VcsVersion @@ -30,44 +29,47 @@ trait BasePublishModule override def pomSettings = PomSettings( description = "Bundler for Mill", - organization = "io.github.nafg.millbundler", - url = "https://github.com/nafg/mill-bundler", + organization = "io.github.thijsbroersen.millbundler", + url = "https://github.com/ThijsBroersen/mill-bundler", licenses = Seq(License.`Apache-2.0`), versionControl = - VersionControl.github(owner = "nafg", repo = "mill-bundler"), - developers = - Seq(Developer("nafg", "Naftoli Gugenheim", "https://github.com/nafg")) + VersionControl.github(owner = "ThijsBroersen", repo = "mill-bundler"), + developers = Seq( + Developer( + "ThijsBroersen", + "Thijs Broersen", + "https://github.com/ThijsBroersen" + ), + Developer("nafg", "Naftoli Gugenheim", "https://github.com/nafg") + ) ) override def scalacOptions = Seq("-Ywarn-unused", "-deprecation") override def mvnDeps = super.mvnDeps() ++ Seq( - mvn"com.lihaoyi::mill-libs:${millVersion}" + mvn"com.lihaoyi::mill-libs:$millVersion" ) -} -object test_common extends BaseScalaModule { +end BasePublishModule + +object test_common extends BaseScalaModule: override def moduleDeps = Seq(jsdeps) override def mvnDeps = Seq( - mvn"com.lihaoyi::mill-testkit:${millVersion}", - mvn"org.scalameta::munit::1.1.1" + mvn"com.lihaoyi::mill-testkit:$millVersion", + mvn"org.scalameta::munit::1.3.6" ) -} -object jsdeps extends BasePublishModule { - object test extends ScalaTests with TestModule.Munit { +object jsdeps extends BasePublishModule: + + object test extends ScalaTests with TestModule.Munit: override def moduleDeps = super.moduleDeps :+ test_common - } -} //noinspection ScalaUnusedSymbol -object millbundler extends BasePublishModule { +object millbundler extends BasePublishModule: override def moduleDeps = Seq(jsdeps) override def mvnDeps = Seq(mvn"com.lihaoyi::geny:1.1.1") - object test extends ScalaTests with TestModule.Munit { + object test extends ScalaTests with TestModule.Munit: override def moduleDeps = super.moduleDeps :+ test_common override def testParallelism = true - } -} diff --git a/jsdeps/src/io/github/nafg/millbundler/jsdeps/JsDeps.scala b/jsdeps/src/io/github/nafg/millbundler/jsdeps/JsDeps.scala index f223cd2..b9e556f 100644 --- a/jsdeps/src/io/github/nafg/millbundler/jsdeps/JsDeps.scala +++ b/jsdeps/src/io/github/nafg/millbundler/jsdeps/JsDeps.scala @@ -15,15 +15,19 @@ case class JsDeps( /** Javascript source files, as a map from path to contents */ jsSources: Map[String, String] = Map.empty -) { +): + def ++(that: JsDeps): JsDeps = JsDeps( dependencies ++ that.dependencies, devDependencies ++ that.devDependencies, jsSources ++ that.jsSources ) -} -object JsDeps { + +end JsDeps + +object JsDeps: + def apply(dependencies: (String, String)*): JsDeps = JsDeps(dependencies = dependencies.toMap) @@ -36,17 +40,15 @@ object JsDeps { in: InputStream, buffer: Array[Byte] = new Array[Byte](8192), out: ByteArrayOutputStream = new ByteArrayOutputStream - ): String = { + ): String = val byteCount = in.read(buffer) - if (byteCount < 0) - out.toString - else { + if byteCount < 0 then out.toString + else out.write(buffer, 0, byteCount) readAllBytes(in, buffer, out) - } - } + end readAllBytes - def fromJar(jar: os.Path): Seq[JsDeps] = { + def fromJar(jar: os.Path): Seq[JsDeps] = val stream = new ZipInputStream( new BufferedInputStream(new FileInputStream(jar.toIO)) ) @@ -80,5 +82,7 @@ object JsDeps { .toList finally stream.close() - } -} + end try + end fromJar + +end JsDeps diff --git a/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSDepsModule.scala b/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSDepsModule.scala index 3ce0b80..826c1c2 100644 --- a/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSDepsModule.scala +++ b/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSDepsModule.scala @@ -6,7 +6,7 @@ import mill.scalajslib.ScalaJSModule import os.Path //noinspection ScalaUnusedSymbol,ScalaWeakerAccess -trait ScalaJSDepsModule extends ScalaJSModule { +trait ScalaJSDepsModule extends ScalaJSModule: /** JS dependencies, explicitly defined for this module */ @@ -15,9 +15,10 @@ trait ScalaJSDepsModule extends ScalaJSModule { /** JS dependencies of moduleDeps, transitively. */ def transitiveJsDeps = Task.sequence( - recursiveModuleDeps.collect { case mod: ScalaJSDepsModule => - mod.allJsDeps - // case mod: ScalaJsModule => mod.recursiveModuleDeps + recursiveModuleDeps.collect { + case mod: ScalaJSDepsModule => + mod.allJsDeps + // case mod: ScalaJsModule => mod.recursiveModuleDeps } ) @@ -35,4 +36,5 @@ trait ScalaJSDepsModule extends ScalaJSModule { final def allJsDeps: Task.Simple[JsDeps] = Task { JsDeps.combine(mvnJsDeps() ++ transitiveJsDeps() :+ jsDeps()) } -} + +end ScalaJSDepsModule diff --git a/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSNpmModule.scala b/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSNpmModule.scala index 8a2d6f6..36da0a6 100644 --- a/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSNpmModule.scala +++ b/jsdeps/src/io/github/nafg/millbundler/jsdeps/ScalaJSNpmModule.scala @@ -1,39 +1,39 @@ package io.github.nafg.millbundler.jsdeps import mill.* +import mill.api.BuildCtx import mill.scalajslib.TestScalaJSModule import mill.scalajslib.api.JsEnvConfig -import mill.api.BuildCtx //noinspection ScalaUnusedSymbol,ScalaWeakerAccess -trait ScalaJSNpmModule extends ScalaJSDepsModule { +trait ScalaJSNpmModule extends ScalaJSDepsModule: + def npmCommand = Task { - if (System.getProperty("os.name").toLowerCase.contains("windows")) + if System.getProperty("os.name").toLowerCase.contains("windows") then "npm.cmd" - else - "npm" + else "npm" } def npmInstallCommand = - Task { Seq(npmCommand(), "install", "--force") } + Task(Seq(npmCommand(), "install", "--force")) - protected def packageJson(deps: JsDeps) = - ujson.Obj( - "dependencies" -> deps.dependencies, - "devDependencies" -> deps.devDependencies - ) + protected def packageJson: Task[JsDeps => ujson.Obj] = Task.Anon { + (deps: JsDeps) => + ujson.Obj( + "dependencies" -> deps.dependencies, + "devDependencies" -> deps.devDependencies + ) + } def npmInstall = Task { - val pkgJson = packageJson(allJsDeps()) + val pkgJson = packageJson()(allJsDeps()) os.write.over(Task.dest / "package.json", pkgJson.render(2) + "\n") - try - os.call(npmInstallCommand(), cwd = Task.dest) - catch { + try os.call(npmInstallCommand(), cwd = Task.dest) + catch case e: Exception => throw new RuntimeException("Error running npm install", e) - } PathRef(Task.dest) } @@ -57,23 +57,24 @@ trait ScalaJSNpmModule extends ScalaJSDepsModule { os.call(Seq("npm", "view", pkg, "dist-tags.latest")).out.trim() ) val updates = latestVersions.filter(x => x._2 != x._3) - if (updates.nonEmpty) { + if updates.nonEmpty then logger.info( s"$BOLD$proj $RESET${updates.length} new npm package versions" ) - for ((pkg, cur, latest) <- updates) + for (pkg, cur, latest) <- updates do logger.info( s" $BOLD${pad(pkg, maxPkgLen)}$RESET ${pad(cur, maxVerLen)} -> $latest" ) - } } -} + +end ScalaJSNpmModule + //noinspection ScalaWeakerAccess -object ScalaJSNpmModule { - trait Test extends TestScalaJSModule with ScalaJSNpmModule { +object ScalaJSNpmModule: + + trait Test extends TestScalaJSModule with ScalaJSNpmModule: + override def jsEnvConfig = Task { val path = npmInstall().path / "node_modules" JsEnvConfig.NodeJs(env = Map("NODE_PATH" -> path.toString)) } - } -} diff --git a/jsdeps/test/resources/simple/src/Tests.scala b/jsdeps/test/resources/simple/src/Tests.scala index 030284e..5365937 100644 --- a/jsdeps/test/resources/simple/src/Tests.scala +++ b/jsdeps/test/resources/simple/src/Tests.scala @@ -1,10 +1,11 @@ -import io.github.nafg.scalajs.facades.reactphonenumberinput._ -import munit.Assertions._ +import io.github.nafg.scalajs.facades.reactphonenumberinput.* +import munit.Assertions.* + import scala.scalajs.js -import scala.scalajs.js.annotation._ +import scala.scalajs.js.annotation.* + +class Tests extends munit.FunSuite: -class Tests extends munit.FunSuite { test("ReactPhoneNumberInput is defined (simple)") { assert(!js.isUndefined(ReactPhoneNumberInput.raw)) } -} diff --git a/jsdeps/test/src/io/github/nafg/millbundler/jsdeps/JsDepsSuite.scala b/jsdeps/test/src/io/github/nafg/millbundler/jsdeps/JsDepsSuite.scala index 0204f37..67705a2 100644 --- a/jsdeps/test/src/io/github/nafg/millbundler/jsdeps/JsDepsSuite.scala +++ b/jsdeps/test/src/io/github/nafg/millbundler/jsdeps/JsDepsSuite.scala @@ -1,19 +1,20 @@ package io.github.nafg.millbundler.jsdeps import io.github.nafg.millbundler.testcommon.BaseSuite + import mill.api.Discover import mill.util.TokenReaders.* -class JsDepsSuite extends BaseSuite { +class JsDepsSuite extends BaseSuite: + test("JsDeps") { - object build extends BaseBuild with ScalaJSNpmModule { - object test extends BaseTestModule with ScalaJSNpmModule.Test { + object build extends BaseBuild with ScalaJSNpmModule: + object test extends BaseTestModule with ScalaJSNpmModule.Test: lazy val millDiscover = Discover[this.type] - } lazy val millDiscover = Discover[test.type] - } checkTestResults(build.test, "simple") } -} + +end JsDepsSuite diff --git a/millbundler/src/io/github/nafg/millbundler/BundleParams.scala b/millbundler/src/io/github/nafg/millbundler/BundleParams.scala index aae45c8..7871cb8 100644 --- a/millbundler/src/io/github/nafg/millbundler/BundleParams.scala +++ b/millbundler/src/io/github/nafg/millbundler/BundleParams.scala @@ -2,7 +2,7 @@ package io.github.nafg.millbundler case class BundleParams(inputFiles: Seq[os.Path], opt: Boolean) -object BundleParams { +object BundleParams: + def apply(inputFile: os.Path, opt: Boolean): BundleParams = BundleParams(Seq(inputFile), opt) -} diff --git a/millbundler/src/io/github/nafg/millbundler/ScalaJSBundleModule.scala b/millbundler/src/io/github/nafg/millbundler/ScalaJSBundleModule.scala index 1452398..7438fa2 100644 --- a/millbundler/src/io/github/nafg/millbundler/ScalaJSBundleModule.scala +++ b/millbundler/src/io/github/nafg/millbundler/ScalaJSBundleModule.scala @@ -1,25 +1,82 @@ package io.github.nafg.millbundler +import io.github.nafg.millbundler.jsdeps.JsDeps import io.github.nafg.millbundler.jsdeps.ScalaJSNpmModule import mill.* +import mill.PathRef +import mill.T import mill.scalajslib.TestScalaJSModule -import mill.scalajslib.api.{ModuleKind, Report} -import mill.{PathRef, T} +import mill.scalajslib.api.ModuleKind +import mill.scalajslib.api.Report //noinspection ScalaWeakerAccess -trait ScalaJSBundleModule extends ScalaJSNpmModule { - protected def getReportMainFilePath(report: Report): os.Path = - report.dest.path / report.publicModules.head.jsFileName - - def bundleFilename = Task("out-bundle.js") - - def copyInputFile = Task.Anon { (inputFiles: Seq[os.Path]) => - val copied = inputFiles.map(Task.dest / _.last) - for ((inputFile, copiedFile) <- inputFiles.zip(copied)) - if (inputFile != copiedFile) - os.copy.over(inputFile, copiedFile) - copied.map(PathRef(_)) +trait ScalaJSBundleModule extends ScalaJSNpmModule: + + override protected def packageJson: Task[JsDeps => ujson.Obj] = Task.Anon { + val tpe = moduleKind() match + case ModuleKind.CommonJSModule => Some("commonjs") + case ModuleKind.NoModule => None + case ModuleKind.ESModule => Some("module") + (deps: JsDeps) => + ujson.Obj.from( + ujson.Obj( + "name" -> moduleCtx.enclosing, + tpe.map(ujson.Str(_)).map("type" -> _).toSeq* + ).value.toSeq ++ + super.packageJson()(deps).value + ) + } + + protected def getReportMainFilePath(report: Report): Seq[os.Path] = + report.publicModules + .map(module => report.dest.path / module.jsFileName) + .toSeq + + def bundleFilename: T[String] = "out-bundle.js" + def outputEntryFileNames: T[String] = "out-bundle-[name].js" + + protected def expectedBundleFilename( + inputFile: os.Path, + multiEntry: Boolean, + singleFilename: String, + entryFileNames: String + ): String = + if multiEntry then + val (head, tail) = entryFileNames.split("\\[name\\]", -1) match + case Array(head, tail) => (head, tail) + case _ => + throw new RuntimeException( + "Invalid output bundle file names, must contain [name]" + ) + val name = inputFile.last.stripSuffix(".js").stripSuffix(".map") + head + name + tail + else singleFilename + + protected def bundlePaths = Task.Anon { (bundles: Iterable[os.Path]) => + val inputFiles = bundles.toSeq + val singleFilename = bundleFilename() + val entryFileNames = outputEntryFileNames() + inputFiles match + case Seq(_) => + List( + PathRef(Task.dest / singleFilename), + PathRef(Task.dest / (singleFilename + ".map")) + ) + case inputFiles => + inputFiles.flatMap { inputFile => + val outName = expectedBundleFilename( + inputFile, + multiEntry = true, + singleFilename, + entryFileNames + ) + Seq( + PathRef(Task.dest / outName), + PathRef(Task.dest / (outName + ".map")) + ) + } + end match } /** Make the npm install available in the current task's dest so that bundlers @@ -46,30 +103,49 @@ trait ScalaJSBundleModule extends ScalaJSNpmModule { } protected def bundle: Task[BundleParams => Seq[PathRef]] -} +end ScalaJSBundleModule + //noinspection ScalaWeakerAccess -object ScalaJSBundleModule { +object ScalaJSBundleModule: + // noinspection ScalaUnusedSymbol - trait Test extends TestScalaJSModule { this: ScalaJSBundleModule => + trait Test extends TestScalaJSModule: + this: ScalaJSBundleModule => + override def fastLinkJSTest = Task { val report = super.fastLinkJSTest() - bundle.apply()( - BundleParams( - report.publicModules.map(report.dest.path / _.jsFileName).toSeq, - opt = false - ) + val inputModules = report.publicModules.toSeq + val inputPaths = + inputModules.map(module => report.dest.path / module.jsFileName) + val multiEntry = inputPaths.size > 1 + val singleFilename = bundleFilename() + val entryFileNames = outputEntryFileNames() + + val bundles = bundle.apply()( + BundleParams(inputPaths, opt = false) ) - val filename = bundleFilename() - val modules = + val groupedBundles = bundles.groupBy(_.path.last.stripSuffix(".map")) + + val modules = inputModules.zip(inputPaths).map { case (orig, path) => + val outName = expectedBundleFilename( + path, + multiEntry, + singleFilename, + entryFileNames + ) + val bundleGroup = groupedBundles.getOrElse(outName, Nil) Report.Module( - moduleID = "main", - jsFileName = filename, - sourceMapName = Some(filename + ".map"), + moduleID = orig.moduleID, + jsFileName = outName, + sourceMapName = + Some(outName + ".map").filter(_ => bundleGroup.size > 1), moduleKind = ModuleKind.NoModule - ) +: - report.publicModules.toSeq.drop(1) + ) + } Report(publicModules = modules, dest = PathRef(Task.dest)) } - } -} + + end Test + +end ScalaJSBundleModule diff --git a/millbundler/src/io/github/nafg/millbundler/ScalaJSRollupModule.scala b/millbundler/src/io/github/nafg/millbundler/ScalaJSRollupModule.scala index d3f7222..a1d7bf5 100644 --- a/millbundler/src/io/github/nafg/millbundler/ScalaJSRollupModule.scala +++ b/millbundler/src/io/github/nafg/millbundler/ScalaJSRollupModule.scala @@ -2,17 +2,19 @@ package io.github.nafg.millbundler import io.github.nafg.millbundler.jsdeps.JsDeps -import mill.api.PathRef import mill.* +import mill.api.PathRef +import mill.scalajslib.api.ModuleKind //noinspection ScalaWeakerAccess -trait ScalaJSRollupModule extends ScalaJSBundleModule { +trait ScalaJSRollupModule extends ScalaJSBundleModule: def rollupVersion: Task.Simple[String] = "*" def rollupPlugins: Task.Simple[Seq[ScalaJSRollupModule.Plugin]] = Task { Seq[ScalaJSRollupModule.Plugin]( ScalaJSRollupModule.Plugin.core("node-resolve"), - ScalaJSRollupModule.Plugin.core("commonjs") + ScalaJSRollupModule.Plugin.core("commonjs"), + ScalaJSRollupModule.Plugin.core("json") ) } @@ -21,25 +23,78 @@ trait ScalaJSRollupModule extends ScalaJSBundleModule { JsDeps(devDependencies = Map("rollup" -> rollupVersion())) ++ JsDeps.combine(rollupPlugins().map(_.toJsDep)) - def rollupOutputFormat: Task.Simple[ScalaJSRollupModule.OutputFormat] = Task { + def rollupConfigFilename = Task("rollup.config.mjs") + + def rollupOutputFormat: T[ScalaJSRollupModule.OutputFormat] = Task { ScalaJSRollupModule.OutputFormat.IIFE } - def rollupOutputName: Task.Simple[Option[String]] = Task(None) - - protected def rollupCliArgs = Task.Anon { - Seq( - "--file", - (Task.dest / bundleFilename()).toString(), - "--format", - rollupOutputFormat().value - ) ++ - rollupOutputName().toSeq.flatMap(name => Seq("--name", name)) ++ - rollupPlugins().flatMap(_.toCliArgs) + def rollupConfig = Task.Anon { (params: BundleParams) => + val inputFiles = params.inputFiles.toSeq + val (input: String, output: String) = inputFiles match + case Seq() => throw new RuntimeException("No input files") + case Seq(inputFile) => + ujson.Str(inputFile.toString).render() -> + s""" + "file": ${ujson.Str((Task.dest / bundleFilename()).toString).render()} + """.stripMargin + case files => + ujson.Arr( + files.map(_.toString).map(ujson.Str(_)).toSeq* + ).render() -> + s""" + "dir": ${ujson.Str(Task.dest.toString).render()}, + "entryFileNames": ${ujson.Str(outputEntryFileNames()).render()} + """.stripMargin + + val outputFormat = + if inputFiles.size == 1 then rollupOutputFormat().value + else + moduleKind() match + case ModuleKind.ESModule => ScalaJSRollupModule.OutputFormat.ES.value + case ModuleKind.CommonJSModule => + ScalaJSRollupModule.OutputFormat.CJS.value + case ModuleKind.NoModule => ScalaJSRollupModule.OutputFormat.ES.value + + val resolveOptions = + s"""{ modulePaths: [${ujson.Str((npmInstall().path / "node_modules").toString).render()}] }""" + + val plugins = rollupPlugins().distinctBy(_.packageName) + val imports = plugins.map(_.rollupImport).mkString("\n ") + val pluginCalls = + plugins.map(_.rollupCall(resolveOptions)).mkString(", ") + val outputName = + if inputFiles.size == 1 then + rollupOutputName().fold("")(name => + s""""name": ${ujson.Str(name).render()},\n """ + ) + else "" + + s""" + $imports + + export default { + input: $input, + output: { + format: "$outputFormat", + sourcemap: true, + globals: {}, + $outputName$output + }, + plugins: [$pluginCalls] + }\n""".stripMargin } + def rollupOutputName: T[Option[String]] = Task(None) + override protected def bundle = Task.Anon { (params: BundleParams) => - val copied = copyInputFile.apply()(params.inputFiles) + val configPath = Task.dest / rollupConfigFilename() + + os.write.over( + configPath, + rollupConfig()(params) + ) + linkNodeModules() val rollupPath = @@ -50,25 +105,17 @@ trait ScalaJSRollupModule extends ScalaJSBundleModule { Seq( "node", rollupPath.toString, - copied.headOption - .map(_.path.toString) - .getOrElse( - throw new RuntimeException( - "No input files were copied; cannot run rollup" - ) - ) - ) ++ rollupCliArgs(), + "--config", + configPath.toString + ), cwd = Task.dest ) - catch { + catch case e: Exception => throw new RuntimeException("Error running rollup", e) - } + end try - List( - PathRef(Task.dest / bundleFilename()), - PathRef(Task.dest / (bundleFilename() + ".map")) - ) + bundlePaths()(params.inputFiles).toSeq } // noinspection ScalaUnusedSymbol @@ -84,26 +131,49 @@ trait ScalaJSRollupModule extends ScalaJSBundleModule { BundleParams(getReportMainFilePath(fullLinkJS()), opt = true) ) } -} -object ScalaJSRollupModule { + +end ScalaJSRollupModule + +object ScalaJSRollupModule: + case class Plugin( packageName: String, version: String = "*", config: Option[String] = None - ) { + ): def toJsDep = JsDeps(devDependencies = Map(packageName -> version)) - def toCliArgs = Seq("--plugin", packageName + config.fold("")("=" + _)) - } - object Plugin { + + def rollupImport: String = packageName match + case "@rollup/plugin-node-resolve" => + s"import { nodeResolve } from '$packageName';" + case _ => + s"import ${Plugin.bindingName(packageName)} from '$packageName';" + + def rollupCall(resolveOptions: String): String = packageName match + case "@rollup/plugin-node-resolve" => + s"nodeResolve(${config.getOrElse(resolveOptions)})" + case _ => + val binding = Plugin.bindingName(packageName) + config.fold(s"$binding()")(c => s"$binding($c)") + + object Plugin: def core(name: String) = Plugin(s"@rollup/plugin-$name") + private def bindingName(packageName: String): String = + packageName match + case "@rollup/plugin-commonjs" => "commonjs" + case "@rollup/plugin-json" => "json" + case s"@rollup/plugin-$name" => name.replace("-", "") + case _ => + packageName.split('/').last.replaceAll("[^a-zA-Z0-9]", "") + implicit val rw: upickle.default.ReadWriter[Plugin] = upickle.default.macroRW[Plugin] - } case class OutputFormat(value: String) + // noinspection ScalaUnusedSymbol,ScalaWeakerAccess - object OutputFormat { + object OutputFormat: val AMD = OutputFormat("amd") val CJS = OutputFormat("cjs") val ES = OutputFormat("es") @@ -113,8 +183,9 @@ object ScalaJSRollupModule { implicit val rw: upickle.default.ReadWriter[OutputFormat] = upickle.default.macroRW[OutputFormat] - } + + end OutputFormat // noinspection ScalaWeakerAccess trait Test extends ScalaJSRollupModule with ScalaJSBundleModule.Test -} +end ScalaJSRollupModule diff --git a/millbundler/src/io/github/nafg/millbundler/ScalaJSWebpackModule.scala b/millbundler/src/io/github/nafg/millbundler/ScalaJSWebpackModule.scala index 76dd35f..a703063 100644 --- a/millbundler/src/io/github/nafg/millbundler/ScalaJSWebpackModule.scala +++ b/millbundler/src/io/github/nafg/millbundler/ScalaJSWebpackModule.scala @@ -3,17 +3,19 @@ package io.github.nafg.millbundler import io.github.nafg.millbundler.jsdeps.JsDeps import geny.Generator + import mill.* +import mill.scalajslib.api.ModuleKind import os.Path //noinspection ScalaWeakerAccess -trait ScalaJSWebpackModule extends ScalaJSBundleModule { +trait ScalaJSWebpackModule extends ScalaJSBundleModule: // renovate: datasource=npm depName=webpack - def webpackVersion: Task.Simple[String] = "5.101.3" + def webpackVersion: Task.Simple[String] = "5.112.0" // renovate: datasource=npm depName=webpack-cli def webpackCliVersion: Task.Simple[String] = "6.0.1" // renovate: datasource=npm depName=webpack-dev-server - def webpackDevServerVersion: Task.Simple[String] = "5.2.2" + def webpackDevServerVersion: Task.Simple[String] = "5.2.6" def webpackLibraryName: Task.Simple[Option[String]] @@ -29,44 +31,55 @@ trait ScalaJSWebpackModule extends ScalaJSBundleModule { ) ) - protected def webpackConfigJson( - dir: os.Path, - params: BundleParams, - bundleFilename: String, - libraryName: Option[String] - ) = { + protected def webpackConfigJson = Task.Anon { (params: BundleParams) => val libraryOutputCfg = - libraryName - .map(n => Map("library" -> n, "libraryTarget" -> "var")) - .getOrElse(Map.empty) - val outputCfg = - libraryOutputCfg ++ Map( - "path" -> dir.toString, - "filename" -> bundleFilename - ) + webpackLibraryName() + .map(n => ujson.Obj("library" -> n, "libraryTarget" -> "var")) + .getOrElse(ujson.Obj()) + val (entryCfg, outputPaths) = params.inputFiles match + case Seq() => throw new RuntimeException("No input files") + case Seq(inputFile) => + ujson.Str(inputFile.toString) -> + ujson.Obj( + "path" -> Task.dest.toString, + "filename" -> bundleFilename() + ) + case inputFiles => + ujson.Obj.from( + inputFiles.map { inputFile => + val name = inputFile.last.stripSuffix(".js").stripSuffix(".map") + name -> ujson.Str(inputFile.toString) + } + ) -> + ujson.Obj( + "path" -> Task.dest.toString, + "filename" -> outputEntryFileNames() + ) + val outputCfg = ujson.Obj.from( + (outputPaths.value ++ libraryOutputCfg.value).toSeq + ) ujson.Obj( - "mode" -> (if (params.opt) "production" else "development"), + "mode" -> (if params.opt then "production" else "development"), "devtool" -> "source-map", - "entry" -> params.inputFiles.headOption - .map(f => (dir / f.last).toString) - .getOrElse(throw new IllegalArgumentException("inputFiles is empty")), - "output" -> ujson.Obj.from(outputCfg.view.mapValues(ujson.Str(_))), - "context" -> dir.toString + "entry" -> entryCfg, + "output" -> outputCfg, + "context" -> Task.dest.toString, + "resolve" -> ujson.Obj( + "modules" -> ujson.Arr( + ujson.Str((npmInstall().path / "node_modules").toString) + ) + ) ) } - protected def webpackConfig( - dir: Path, - params: BundleParams, - bundleFilename: String, - webpackLibraryName: Option[String] - ) = + protected def webpackConfig = Task.Anon { (params: BundleParams) => "module.exports = " + - webpackConfigJson(dir, params, bundleFilename, webpackLibraryName) + webpackConfigJson()(params) .render(2) + ";\n" + } - def webpackConfigFilename = Task("webpack.config.js") + def webpackConfigFilename = Task("webpack.config.cjs") def webpackEnv: Task.Simple[Map[String, String]] = Task { val nodeMajorVersion = os @@ -88,14 +101,15 @@ trait ScalaJSWebpackModule extends ScalaJSBundleModule { } override protected def bundle = Task.Anon { (params: BundleParams) => - copyInputFile.apply()(params.inputFiles) linkNodeModules() val configPath = Task.dest / webpackConfigFilename() + os.write.over( configPath, - webpackConfig(Task.dest, params, bundleFilename(), webpackLibraryName()) + webpackConfig()(params) ) + val webpackPath = npmInstall().path / "node_modules" / "webpack" / "bin" / "webpack" @@ -105,21 +119,20 @@ trait ScalaJSWebpackModule extends ScalaJSBundleModule { env = webpackEnv(), cwd = Task.dest ) - catch { + catch case e: Exception => throw new RuntimeException("Error running webpack", e) - } - List( - PathRef(Task.dest / bundleFilename()), - PathRef(Task.dest / (bundleFilename() + ".map")) - ) + bundlePaths()(params.inputFiles).toSeq } -} + +end ScalaJSWebpackModule + //noinspection ScalaUnusedSymbol -object ScalaJSWebpackModule { +object ScalaJSWebpackModule: + // noinspection ScalaUnusedSymbol,ScalaWeakerAccess - trait AsApplication extends ScalaJSWebpackModule { + trait AsApplication extends ScalaJSWebpackModule: override def webpackLibraryName: Task.Simple[Option[String]] = Task(None) def devBundle: Task.Simple[Seq[PathRef]] = Task(persistent = true) { @@ -133,18 +146,19 @@ object ScalaJSWebpackModule { BundleParams(getReportMainFilePath(fullLinkJS()), opt = true) ) } - } + + end AsApplication // noinspection ScalaUnusedSymbol,ScalaWeakerAccess - trait AsLibrary extends ScalaJSWebpackModule { + trait AsLibrary extends ScalaJSWebpackModule: private val requireRegex = """require\("([^"]*)"\)""".r override def webpackLibraryName = Some("app") - protected def entrypointScript(depNames: Iterable[String]) = { + protected def entrypointScript(depNames: Iterable[String]) = val requiresMap = depNames - .map { name => s"'$name': require('$name')" } + .map(name => s"'$name': require('$name')") .mkString(",\n ") s""" |module.exports = { @@ -155,17 +169,20 @@ object ScalaJSWebpackModule { | }) |} |""".stripMargin.trim - } + end entrypointScript - def writeEntrypoint = Task.Anon { (src: os.Path) => + def writeEntrypoint = Task.Anon { (srcs: Iterable[os.Path]) => val path = Task.dest / "entrypoint.js" val requires = - os.read.lines - .stream(src) - .flatMap { line => - Generator.from(requireRegex.findAllMatchIn(line).map(_.group(1))) - } - .toList + srcs.flatMap(src => + os.read.lines + .stream(src) + .flatMap { line => + Generator.from(requireRegex.findAllMatchIn(line).map(_.group(1))) + } + .toList + ) + os.write.over( path, entrypointScript(requires) @@ -174,17 +191,22 @@ object ScalaJSWebpackModule { } def devBundle: Task.Simple[Seq[PathRef]] = Task { - val path = getReportMainFilePath(fastLinkJS()) - val entrypoint = writeEntrypoint.apply()(path).path - bundle.apply()(BundleParams(entrypoint, opt = false)) :+ PathRef(path) + val paths = getReportMainFilePath(fastLinkJS()) + val entrypoint = writeEntrypoint.apply()(paths).path + bundle.apply()(BundleParams(entrypoint, opt = false)) ++ paths.map( + PathRef(_) + ) } def prodBundle: Task.Simple[Seq[PathRef]] = Task { - val path = getReportMainFilePath(fullLinkJS()) - val entrypoint = writeEntrypoint.apply()(path).path - bundle.apply()(BundleParams(entrypoint, opt = true)) :+ PathRef(path) + val paths = getReportMainFilePath(fullLinkJS()) + val entrypoint = writeEntrypoint.apply()(paths).path + bundle.apply()(BundleParams(entrypoint, opt = true)) ++ paths.map( + PathRef(_) + ) } - } + + end AsLibrary trait Test extends AsApplication with ScalaJSBundleModule.Test -} +end ScalaJSWebpackModule diff --git a/millbundler/test/resources/multi-entry/entry-a.js b/millbundler/test/resources/multi-entry/entry-a.js new file mode 100644 index 0000000..bdf320d --- /dev/null +++ b/millbundler/test/resources/multi-entry/entry-a.js @@ -0,0 +1 @@ +module.exports = { name: "entry-a" }; diff --git a/millbundler/test/resources/multi-entry/entry-b.js b/millbundler/test/resources/multi-entry/entry-b.js new file mode 100644 index 0000000..2d53c67 --- /dev/null +++ b/millbundler/test/resources/multi-entry/entry-b.js @@ -0,0 +1 @@ +module.exports = { name: "entry-b" }; diff --git a/millbundler/test/resources/multi-entry/src/Dummy.scala b/millbundler/test/resources/multi-entry/src/Dummy.scala new file mode 100644 index 0000000..c761d4f --- /dev/null +++ b/millbundler/test/resources/multi-entry/src/Dummy.scala @@ -0,0 +1,3 @@ +package dummy + +object Dummy diff --git a/millbundler/test/resources/rollup-split-app/src/Main.scala b/millbundler/test/resources/rollup-split-app/src/Main.scala new file mode 100644 index 0000000..d6d3296 --- /dev/null +++ b/millbundler/test/resources/rollup-split-app/src/Main.scala @@ -0,0 +1,4 @@ +package main + +object Main: + def main(args: Array[String]): Unit = () diff --git a/millbundler/test/resources/rollup-split-app/src/extra/ExtraEntry.scala b/millbundler/test/resources/rollup-split-app/src/extra/ExtraEntry.scala new file mode 100644 index 0000000..20d880d --- /dev/null +++ b/millbundler/test/resources/rollup-split-app/src/extra/ExtraEntry.scala @@ -0,0 +1,7 @@ +package extra + +import scala.scalajs.js.annotation.* + +@JSExportTopLevel("extraEntry", moduleID = "extra") +object ExtraEntry: + def value: Int = 1 diff --git a/millbundler/test/resources/rollup/src/Tests.scala b/millbundler/test/resources/rollup/src/Tests.scala index 085748a..b97888e 100644 --- a/millbundler/test/resources/rollup/src/Tests.scala +++ b/millbundler/test/resources/rollup/src/Tests.scala @@ -1,10 +1,11 @@ -import io.github.nafg.scalajs.facades.reactphonenumberinput._ -import munit.Assertions._ +import io.github.nafg.scalajs.facades.reactphonenumberinput.* +import munit.Assertions.* + import scala.scalajs.js -import scala.scalajs.js.annotation._ +import scala.scalajs.js.annotation.* + +class Tests extends munit.FunSuite: -class Tests extends munit.FunSuite { test("ReactPhoneNumberInput is defined (rollup)") { assert(!js.isUndefined(ReactPhoneNumberInput.raw)) } -} diff --git a/millbundler/test/resources/webpack-library/src/App.scala b/millbundler/test/resources/webpack-library/src/App.scala new file mode 100644 index 0000000..a5f0488 --- /dev/null +++ b/millbundler/test/resources/webpack-library/src/App.scala @@ -0,0 +1,4 @@ +package app + +object App: + def main(args: Array[String]): Unit = () diff --git a/millbundler/test/resources/webpack-simple/src/Tests.scala b/millbundler/test/resources/webpack-simple/src/Tests.scala index e84848d..d1a5d5c 100644 --- a/millbundler/test/resources/webpack-simple/src/Tests.scala +++ b/millbundler/test/resources/webpack-simple/src/Tests.scala @@ -1,10 +1,11 @@ -import io.github.nafg.scalajs.facades.reactphonenumberinput._ -import munit.Assertions._ +import io.github.nafg.scalajs.facades.reactphonenumberinput.* +import munit.Assertions.* + import scala.scalajs.js -import scala.scalajs.js.annotation._ +import scala.scalajs.js.annotation.* + +class Tests extends munit.FunSuite: -class Tests extends munit.FunSuite { test("ReactPhoneNumberInput is defined (webpack-simple)") { assert(!js.isUndefined(ReactPhoneNumberInput.raw)) } -} diff --git a/millbundler/test/resources/webpack-split-app/src/Main.scala b/millbundler/test/resources/webpack-split-app/src/Main.scala new file mode 100644 index 0000000..d6d3296 --- /dev/null +++ b/millbundler/test/resources/webpack-split-app/src/Main.scala @@ -0,0 +1,4 @@ +package main + +object Main: + def main(args: Array[String]): Unit = () diff --git a/millbundler/test/resources/webpack-split-app/src/extra/ExtraEntry.scala b/millbundler/test/resources/webpack-split-app/src/extra/ExtraEntry.scala new file mode 100644 index 0000000..20d880d --- /dev/null +++ b/millbundler/test/resources/webpack-split-app/src/extra/ExtraEntry.scala @@ -0,0 +1,7 @@ +package extra + +import scala.scalajs.js.annotation.* + +@JSExportTopLevel("extraEntry", moduleID = "extra") +object ExtraEntry: + def value: Int = 1 diff --git a/millbundler/test/src/io/github/nafg/millbundler/RollupSuite.scala b/millbundler/test/src/io/github/nafg/millbundler/RollupSuite.scala index 1bd08c6..345e58c 100644 --- a/millbundler/test/src/io/github/nafg/millbundler/RollupSuite.scala +++ b/millbundler/test/src/io/github/nafg/millbundler/RollupSuite.scala @@ -1,23 +1,150 @@ package io.github.nafg.millbundler import io.github.nafg.millbundler.testcommon.BaseSuite + +import mill.* import mill.api.Discover +import mill.scalajslib.api.{ModuleKind, ModuleSplitStyle} +import mill.testkit.TestRootModule import mill.util.TokenReaders.* -class RollupSuite extends BaseSuite { +class RollupSuite extends BaseSuite: + test("Rollup") { - object build extends BaseBuild { - object test extends BaseTestModule with ScalaJSRollupModule.Test { - override def rollupPlugins = - super.rollupPlugins() :+ - ScalaJSRollupModule.Plugin.core("json") + object build extends BaseBuild: + object test extends BaseTestModule with ScalaJSRollupModule.Test: + override def rollupOutputName = Some("RollupTest") + + override def moduleKind = ModuleKind.ESModule lazy val millDiscover = Discover[this.type] - } lazy val millDiscover = Discover[test.type] - } + end build checkTestResults(build.test, "rollup") } -} + + test("Rollup - multi entry") { + val inputs = Seq(multiEntryDir / "entry-a.js", multiEntryDir / "entry-b.js") + + object build extends BaseBuild: + object bundleTest extends TestRootModule with ScalaJSRollupModule: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + + def runMultiBundle = Task { + bundle.apply()(BundleParams(inputs, opt = false)) + } + + def runRollupConfig = Task { + rollupConfig()(BundleParams(inputs, opt = false)) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[bundleTest.type] + end build + + val config = + evalTask(build.bundleTest, "multi-entry", build.bundleTest.runRollupConfig) + assert(config.contains("\"dir\":")) + assert(config.contains("sourcemap: true")) + assert(config.contains("entry-a.js")) + assert(config.contains("entry-b.js")) + assert(!config.contains("\"name\": \"RollupTest\"")) + + val bundles = + evalTask(build.bundleTest, "multi-entry", build.bundleTest.runMultiBundle) + val outputs = bundles.map(_.path.last).toSet + assert(outputs.contains("out-bundle-entry-a.js")) + assert(outputs.contains("out-bundle-entry-b.js")) + assert(outputs.contains("out-bundle-entry-a.js.map")) + assert(outputs.contains("out-bundle-entry-b.js.map")) + assertExistingBundles(bundles) + } + + test("Rollup - empty input fails") { + object build extends BaseBuild: + object bundleTest extends TestRootModule with ScalaJSRollupModule: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + + def runBundle = Task { + bundle.apply()(BundleParams(Nil, opt = false)) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[bundleTest.type] + end build + + val err = + evalTaskExpectFailure( + build.bundleTest, + "multi-entry", + build.bundleTest.runBundle + ) + assert( + err.getMessage.contains("No input files") || + Option(err.getCause).exists(_.getMessage.contains("No input files")) + ) + } + + test("Rollup - split modules") { + object build extends BaseBuild: + object app extends TestRootModule with ScalaJSRollupModule: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + override def moduleKind = ModuleKind.CommonJSModule + override def moduleSplitStyle = ModuleSplitStyle.FewestModules + + def runSplitBundle = Task { + val report = fastLinkJS() + val paths = getReportMainFilePath(report).toSeq + assert( + paths.size > 1, + s"expected multiple public modules, got ${paths.size}: ${paths.mkString(", ")}" + ) + bundle.apply()(BundleParams(paths, opt = false)) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[app.type] + end build + + val bundles = + evalTask(build.app, "rollup-split-app", build.app.runSplitBundle) + assert(bundles.size >= 2) + assertExistingBundles(bundles) + } + + test("Rollup - output name in config") { + val inputs = Seq(multiEntryDir / "entry-a.js") + + object build extends BaseBuild: + object bundleTest extends TestRootModule with ScalaJSRollupModule: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + override def rollupOutputName = Some("RollupTest") + + def runRollupConfig = Task { + rollupConfig()(BundleParams(inputs, opt = false)) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[bundleTest.type] + end build + + val config = + evalTask(build.bundleTest, "multi-entry", build.bundleTest.runRollupConfig) + assert(config.contains("\"name\": \"RollupTest\"")) + } + +end RollupSuite diff --git a/millbundler/test/src/io/github/nafg/millbundler/WebpackSuite.scala b/millbundler/test/src/io/github/nafg/millbundler/WebpackSuite.scala index 7f97124..e1a8d77 100644 --- a/millbundler/test/src/io/github/nafg/millbundler/WebpackSuite.scala +++ b/millbundler/test/src/io/github/nafg/millbundler/WebpackSuite.scala @@ -1,19 +1,183 @@ package io.github.nafg.millbundler import io.github.nafg.millbundler.testcommon.BaseSuite + +import mill.* import mill.api.Discover +import mill.scalajslib.api.{ModuleKind, ModuleSplitStyle} +import mill.testkit.TestRootModule import mill.util.TokenReaders.* -class WebpackSuite extends BaseSuite { +class WebpackSuite extends BaseSuite: + test("Webpack - simple") { - object build extends BaseBuild { - object test extends BaseTestModule with ScalaJSWebpackModule.Test { + object build extends BaseBuild: + object test extends BaseTestModule with ScalaJSWebpackModule.Test: lazy val millDiscover = Discover[this.type] - } lazy val millDiscover = Discover[test.type] - } + end build checkTestResults(build.test, "webpack-simple") } -} + + test("Webpack - multi entry") { + val inputs = Seq(multiEntryDir / "entry-a.js", multiEntryDir / "entry-b.js") + + object build extends BaseBuild: + object bundleTest extends TestRootModule with ScalaJSWebpackModule.AsApplication: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + override def outputEntryFileNames: T[String] = "bundle-[name].js" + + def runMultiBundle = Task { + bundle.apply()(BundleParams(inputs, opt = false)) + } + + def runWebpackConfig = Task { + webpackConfig()(BundleParams(inputs, opt = false)) + } + + def runConfigFilename = Task { + webpackConfigFilename() + } + + def runTrailingNameTemplate = Task { + expectedBundleFilename( + os.pwd / "entry-a.js", + multiEntry = true, + "unused.js", + "bundle-[name]" + ) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[bundleTest.type] + end build + + val config = + evalTask(build.bundleTest, "multi-entry", build.bundleTest.runWebpackConfig) + assert(config.contains("\"entry-a\"")) + assert(config.contains("\"entry-b\"")) + assert(config.contains("entry-a.js")) + assert(config.contains("entry-b.js")) + assert(config.contains("bundle-[name].js")) + assert( + evalTask( + build.bundleTest, + "multi-entry", + build.bundleTest.runConfigFilename + ) == "webpack.config.cjs" + ) + assert( + evalTask( + build.bundleTest, + "multi-entry", + build.bundleTest.runTrailingNameTemplate + ) == "bundle-entry-a" + ) + + val bundles = + evalTask(build.bundleTest, "multi-entry", build.bundleTest.runMultiBundle) + val outputs = bundles.map(_.path.last).toSet + assert(outputs.contains("bundle-entry-a.js")) + assert(outputs.contains("bundle-entry-b.js")) + assert(outputs.contains("bundle-entry-a.js.map")) + assert(outputs.contains("bundle-entry-b.js.map")) + assertExistingBundles(bundles) + } + + test("Webpack - empty input fails") { + object build extends BaseBuild: + object bundleTest extends TestRootModule with ScalaJSWebpackModule.AsApplication: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + + def runBundle = Task { + bundle.apply()(BundleParams(Nil, opt = false)) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[bundleTest.type] + end build + + val err = + evalTaskExpectFailure( + build.bundleTest, + "multi-entry", + build.bundleTest.runBundle + ) + assert( + err.getMessage.contains("No input files") || + Option(err.getCause).exists(_.getMessage.contains("No input files")) + ) + } + + test("Webpack - split modules") { + object build extends BaseBuild: + object app extends TestRootModule with ScalaJSWebpackModule.AsApplication: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + override def moduleKind = ModuleKind.CommonJSModule + override def moduleSplitStyle = ModuleSplitStyle.FewestModules + + def runSplitBundle = Task { + val report = fastLinkJS() + val paths = getReportMainFilePath(report).toSeq + assert( + paths.size > 1, + s"expected multiple public modules, got ${paths.size}: ${paths.mkString(", ")}" + ) + bundle.apply()(BundleParams(paths, opt = false)) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[app.type] + end build + + val bundles = + evalTask(build.app, "webpack-split-app", build.app.runSplitBundle) + assert(bundles.size >= 2) + assertExistingBundles(bundles) + } + + test("Webpack - as library") { + object build extends BaseBuild: + object frontend extends TestRootModule with ScalaJSWebpackModule.AsLibrary: + override def moduleDeps = Seq(build) + override def scalaVersion = build.scalaVersion + override def scalaJSVersion = build.scalaJSVersion + + def runDevBundle = Task { + devBundle() + } + + def runEntrypoint = Task { + entrypointScript(Seq("left-pad")) + } + + lazy val millDiscover = Discover[this.type] + + lazy val millDiscover = Discover[frontend.type] + end build + + val script = + evalTask(build.frontend, "webpack-library", build.frontend.runEntrypoint) + assert(script.contains("require('left-pad')")) + assert(!script.contains("require.resolve")) + + val bundles = + evalTask(build.frontend, "webpack-library", build.frontend.runDevBundle) + val outputNames = bundles.map(_.path.last).toSet + assert(outputNames.contains("out-bundle.js")) + assert(bundles.exists(_.path.ext == "js")) + assertExistingBundles(bundles) + } + +end WebpackSuite diff --git a/renovate.json5 b/renovate.json5 index f23176f..9c85195 100644 --- a/renovate.json5 +++ b/renovate.json5 @@ -11,7 +11,7 @@ ], matchStrings: [ // Match comment above a Scala def version definition - "//\\s*renovate:\\s*datasource=(?[^\\s]+)\\s+depName=(?[^\\s]+)[^\\n]*\\n\\s*def\\s+\\S+\\s*:\\s*Target\\[String\\]\\s*=\\s*\\\"(?[^\\\"]+)\\\"", + "//\\s*renovate:\\s*datasource=(?[^\\s]+)\\s+depName=(?[^\\s]+)[^\\n]*\\n\\s*def\\s+\\S+\\s*:\\s*(?:Task\\.Simple|Target)\\[String\\]\\s*=\\s*\\\"(?[^\\\"]+)\\\"", // Match comment above a map entry like \"pkg\" -> \"1.2.3\" "//\\s*renovate:\\s*datasource=(?[^\\s]+)\\s+depName=(?[^\\s]+)[^\\n]*\\n\\s*\\\"[^\\\"]+\\\"\\s*->\\s*\\\"(?[^\\\"]+)\\\"" ], diff --git a/test_common/src/io/github/nafg/millbundler/testcommon/BaseSuite.scala b/test_common/src/io/github/nafg/millbundler/testcommon/BaseSuite.scala index 16c9859..00206f0 100644 --- a/test_common/src/io/github/nafg/millbundler/testcommon/BaseSuite.scala +++ b/test_common/src/io/github/nafg/millbundler/testcommon/BaseSuite.scala @@ -1,27 +1,31 @@ package io.github.nafg.millbundler.testcommon -import scala.concurrent.duration.DurationInt - import io.github.nafg.millbundler.jsdeps.ScalaJSDepsModule +import scala.concurrent.duration.DurationInt + import mill.* -import mill.scalajslib.api.ModuleKind -import mill.scalalib.{DepSyntax, TestModule} -import mill.testkit.{TestRootModule, UnitTester} +import mill.javalib.JavaModule import mill.javalib.testrunner.TestResult +import mill.scalajslib.api.ModuleKind +import mill.scalalib.DepSyntax +import mill.scalalib.TestModule +import mill.testkit.TestRootModule +import mill.testkit.UnitTester -class BaseSuite extends munit.FunSuite { +class BaseSuite extends munit.FunSuite: override def munitTimeout = 4.minute - private val resourceFolder = os.Path(sys.env("MILL_TEST_RESOURCE_DIR")) + protected val resourceFolder = os.Path(sys.env("MILL_TEST_RESOURCE_DIR")) + + protected def multiEntryDir: os.Path = resourceFolder / "multi-entry" - protected def checkTestResults(testResults: Seq[TestResult]): Unit = { + protected def checkTestResults(testResults: Seq[TestResult]): Unit = assert(testResults.nonEmpty, "No tests found") assert( testResults.forall(_.status == "Success"), "Some tests failed" ) - } protected def checkTestResults( test: BaseBuild#BaseTestModule, @@ -29,27 +33,63 @@ class BaseSuite extends munit.FunSuite { ): Unit = UnitTester(test, resourceFolder / name) .scoped { tester => - tester(test.testCached) match { + tester(test.testCached) match + case Left(failing) => failing.throwException + case Right(UnitTester.Result((_, results), _)) => + checkTestResults(results) + } + + protected def evalTask[A]( + module: TestRootModule, + resourceName: String, + task: Task[A] + ): A = + UnitTester(module, resourceFolder / resourceName) + .scoped { tester => + tester(task) match case Left(failing) => failing.throwException - case Right(UnitTester.Result((_, result), _)) => - checkTestResults(result) - } + case Right(UnitTester.Result(value, _)) => value.asInstanceOf[A] } - abstract class BaseBuild extends TestRootModule with ScalaJSDepsModule { - override def scalaVersion = "3.7.2" - override def scalaJSVersion = "1.19.0" + protected def assertExistingBundles(bundles: Seq[PathRef]): Unit = + assert(bundles.nonEmpty, "expected bundle outputs") + bundles.foreach { ref => + assert(os.exists(ref.path), s"missing bundle output ${ref.path}") + } + + protected def evalTaskExpectFailure( + module: TestRootModule, + resourceName: String, + task: Task[?] + ): Throwable = + try + evalTask(module, resourceName, task) + throw new AssertionError(s"Expected $task to fail") + catch + case e: AssertionError => throw e + case e: Throwable => e + + abstract class BaseBuild extends TestRootModule with ScalaJSDepsModule: + override def scalaVersion = "3.8.2" + override def scalaJSVersion = "1.22.0" abstract class BaseTestModule extends TestRootModule with ScalaJSTests - with TestModule.Munit { + with TestModule.Munit: + /** Pin outer module — extra `TestScalaJSModule` mixins must not erase `JavaTests.moduleDeps`. */ + override def moduleDeps: Seq[JavaModule] = Seq(BaseBuild.this) + override def moduleKind = ModuleKind.CommonJSModule + override def mvnDeps = super.mvnDeps() ++ Seq( - mvn"org.scalameta::munit::1.1.1", - mvn"io.github.nafg.scalajs-facades::react-phone-number-input_3::0.16.0" + mvn"org.scalameta::munit::1.3.6", + mvn"io.github.nafg.scalajs-facades::react-phone-number-input_3::0.19.0" ) - } - } -} + + end BaseTestModule + + end BaseBuild + +end BaseSuite