webpack.config.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { dirname, join } from "path";
  2. import { exec } from "child_process";
  3. import { fileURLToPath } from "url";
  4. import dotenv from "dotenv";
  5. import MiniCssExtractPlugin from "mini-css-extract-plugin";
  6. import CssMinimizerPlugin from "css-minimizer-webpack-plugin";
  7. dotenv.config();
  8. /** Set to true to suppress all webpack output but errors */
  9. const silent = true;
  10. const defaultMode = ["development", "production"].includes(process.env.NODE_ENV) ? String(process.env.NODE_ENV) : "development";
  11. const outFileSuffix = process.env.OUTFILE_SUFFIX ?? "";
  12. /** Webpack configuration for the output file */
  13. const output = {
  14. filename: `BetterYTM${outFileSuffix}.user.js`,
  15. path: join(dirname(fileURLToPath(import.meta.url)), "/dist"),
  16. clean: true,
  17. module: true,
  18. };
  19. /** @param {import("./src/types").WebpackEnv} env */
  20. const getConfig = (env) => {
  21. /** @type {import("webpack").Configuration} */
  22. const cfg = {
  23. entry: "./src/index.ts",
  24. output,
  25. experiments: {
  26. // userscripts are automatically wrapped in an IIFE by the browser extension,
  27. // also all modern browsers support ESM so this can safely be enabled:
  28. outputModule: true,
  29. },
  30. mode: env.mode ?? defaultMode,
  31. resolve: {
  32. extensions: [
  33. ".ts",
  34. ".js",
  35. ".css",
  36. ".md",
  37. ],
  38. },
  39. module: {
  40. rules: [
  41. {
  42. test: /\.tsx?$/,
  43. use: "ts-loader",
  44. exclude: /node_modules/,
  45. },
  46. {
  47. test: /\.(html|svg)$/i,
  48. loader: "html-loader",
  49. },
  50. {
  51. test: /\.md$/,
  52. use: [
  53. {
  54. loader: "html-loader",
  55. },
  56. {
  57. loader: "markdown-loader",
  58. },
  59. ],
  60. },
  61. {
  62. test: /.css$/,
  63. use: [MiniCssExtractPlugin.loader, "css-loader" /*, "sass-loader"*/],
  64. },
  65. ],
  66. },
  67. optimization: {
  68. minimizer: [
  69. `...`,
  70. new CssMinimizerPlugin(),
  71. ],
  72. },
  73. plugins: [
  74. new MiniCssExtractPlugin({
  75. filename: "global.css",
  76. }),
  77. {
  78. apply: (compiler) => {
  79. console.log("Running post-build script...\n");
  80. compiler.hooks.afterEmit.tap("AfterEmitPlugin", () => {
  81. exec(`npm run --silent post-build -- mode=${env.mode ?? defaultMode}`, (_err, stdout, stderr) => {
  82. stdout && process.stdout.write(stdout);
  83. stderr && process.stderr.write(stderr);
  84. });
  85. });
  86. },
  87. },
  88. ],
  89. devtool: "source-map",
  90. ...(silent ? { stats: "errors-only", } : {}),
  91. };
  92. return cfg;
  93. };
  94. export default getConfig;
  95. export { output };