webpack.config.js 2.2 KB

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