webpack.config.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. const HtmlWebpackPlugin = require('html-webpack-plugin');
  2. const CopyPlugin = require("copy-webpack-plugin");
  3. const HtmlMinimizerPlugin = require("html-minimizer-webpack-plugin");
  4. const { CleanWebpackPlugin } = require("clean-webpack-plugin");
  5. const MiniCssExtractPlugin = require("mini-css-extract-plugin");
  6. const CompressionPlugin = require("compression-webpack-plugin");
  7. const TerserPlugin = require("terser-webpack-plugin");
  8. const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
  9. const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
  10. const webpack = require("webpack");
  11. const path = require("path");
  12. const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  13. const globSync = require("glob").sync;
  14. const glob = require('glob');
  15. const { merge } = require('webpack-merge');
  16. const devserver = require('./webpack/webpack.dev.js');
  17. const fs = require('fs');
  18. const zlib = require("zlib");
  19. const PurgeCSSPlugin = require('purgecss-webpack-plugin')
  20. const whitelister = require('purgecss-whitelister');
  21. const PATHS = {
  22. src: path.join(__dirname, 'src')
  23. }
  24. class BuildEventsHook {
  25. constructor(name, fn, stage = 'afterEmit') {
  26. this.name = name;
  27. this.stage = stage;
  28. this.function = fn;
  29. }
  30. apply(compiler) {
  31. compiler.hooks[this.stage].tap(this.name, this.function);
  32. }
  33. }
  34. module.exports = (env, options) => (
  35. merge(
  36. env.WEBPACK_SERVE ? devserver : {},
  37. env.ANALYZE_SIZE?{ plugins: [ new BundleAnalyzerPlugin(
  38. {
  39. analyzerMode: 'static',
  40. generateStatsFile: true,
  41. statsFilename: 'stats.json',
  42. }
  43. ) ]}:{},
  44. {
  45. entry:
  46. {
  47. index: './src/index.ts'
  48. },
  49. devtool:"source-map",
  50. module: {
  51. rules: [
  52. {
  53. test: /\.ejs$/,
  54. loader: 'ejs-loader',
  55. options: {
  56. variable: 'data',
  57. interpolate : '\\{\\{(.+?)\\}\\}',
  58. evaluate : '\\[\\[(.+?)\\]\\]'
  59. }
  60. },
  61. {
  62. test: /\.(woff(2)?|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
  63. use: [
  64. {
  65. loader: 'file-loader',
  66. options: {
  67. name: '[name].[ext]',
  68. outputPath: 'fonts/'
  69. }
  70. }
  71. ]
  72. },
  73. // {
  74. // test: /\.s[ac]ss$/i,
  75. // use: [{
  76. // loader: 'style-loader', // inject CSS to page
  77. // },
  78. // {
  79. // loader: MiniCssExtractPlugin.loader,
  80. // options: {
  81. // publicPath: "../",
  82. // },
  83. // },
  84. // "css-loader",
  85. // {
  86. // loader: "postcss-loader",
  87. // options: {
  88. // postcssOptions: {
  89. // plugins: [["autoprefixer"]],
  90. // },
  91. // },
  92. // },
  93. // "sass-loader",
  94. // ]
  95. // },
  96. {
  97. test: /\.(scss)$/,
  98. use: [
  99. {
  100. loader: MiniCssExtractPlugin.loader,
  101. options: {
  102. publicPath: "../",
  103. },
  104. },
  105. // {
  106. // // inject CSS to page
  107. // loader: 'style-loader'
  108. // },
  109. {
  110. // translates CSS into CommonJS modules
  111. loader: 'css-loader'
  112. },
  113. {
  114. // Run postcss actions
  115. loader: 'postcss-loader',
  116. options: {
  117. // `postcssOptions` is needed for postcss 8.x;
  118. // if you use postcss 7.x skip the key
  119. postcssOptions: {
  120. // postcss plugins, can be exported to postcss.config.js
  121. plugins: function () {
  122. return [
  123. require('autoprefixer')
  124. ];
  125. }
  126. }
  127. }
  128. }, {
  129. // compiles Sass to CSS
  130. loader: 'sass-loader'
  131. }]
  132. },
  133. {
  134. test: /\.js$/,
  135. exclude: /(node_modules|bower_components)/,
  136. use: {
  137. loader: "babel-loader",
  138. options: {
  139. presets: ["@babel/preset-env"],
  140. plugins: ['@babel/plugin-transform-runtime']
  141. },
  142. },
  143. },
  144. {
  145. test: /\.(jpe?g|png|gif|svg)$/i,
  146. type: "asset",
  147. },
  148. // {
  149. // test: /\.html$/i,
  150. // type: "asset/resource",
  151. // },
  152. {
  153. test: /\.html$/i,
  154. loader: "html-loader",
  155. options: {
  156. minimize: true,
  157. }
  158. },
  159. {
  160. test: /\.tsx?$/,
  161. use: 'ts-loader',
  162. exclude: /node_modules/,
  163. },
  164. ],
  165. },
  166. plugins: [
  167. new HtmlWebpackPlugin({
  168. title: 'SqueezeESP32',
  169. template: './src/index.ejs',
  170. filename: 'index.html',
  171. inject: 'body',
  172. minify: {
  173. html5 : true,
  174. collapseWhitespace : true,
  175. minifyCSS : true,
  176. minifyJS : true,
  177. minifyURLs : false,
  178. removeAttributeQuotes : true,
  179. removeComments : true, // false for Vue SSR to find app placeholder
  180. removeEmptyAttributes : true,
  181. removeOptionalTags : true,
  182. removeRedundantAttributes : true,
  183. removeScriptTypeAttributes : true,
  184. removeStyleLinkTypeAttributese : true,
  185. useShortDoctype : true
  186. },
  187. favicon: "./src/assets/images/favicon-32x32.png",
  188. excludeChunks: ['test'],
  189. }),
  190. // new CompressionPlugin({
  191. // test: /\.(js|css|html|svg)$/,
  192. // //filename: '[path].br[query]',
  193. // filename: "[path][base].br",
  194. // algorithm: 'brotliCompress',
  195. // compressionOptions: { level: 11 },
  196. // threshold: 100,
  197. // minRatio: 0.8,
  198. // deleteOriginalAssets: false
  199. // }),
  200. new MiniCssExtractPlugin({
  201. filename: "css/[name].[contenthash].css",
  202. }),
  203. new PurgeCSSPlugin({
  204. keyframes: false,
  205. paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, {
  206. nodir: true
  207. }),
  208. whitelist: whitelister('bootstrap/dist/css/bootstrap.css')
  209. }),
  210. new webpack.ProvidePlugin({
  211. $: "jquery",
  212. // jQuery: "jquery",
  213. // "window.jQuery": "jquery",
  214. // Popper: ["popper.js", "default"],
  215. // Util: "exports-loader?Util!bootstrap/js/dist/util",
  216. // Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
  217. }),
  218. new CompressionPlugin({
  219. //filename: '[path].gz[query]',
  220. test: /\.js$|\.css$|\.html$/,
  221. filename: "[path][base].gz",
  222. algorithm: 'gzip',
  223. threshold: 100,
  224. minRatio: 0.8,
  225. }),
  226. new BuildEventsHook('Update C App',
  227. function (stats, arguments) {
  228. if (options.mode !== "production") return;
  229. let buildRootPath = path.join(process.cwd(),'..','..','..');
  230. let wifiManagerPath=glob.sync(path.join(buildRootPath,'components/**/wifi-manager*'))[0];
  231. let buildCRootPath=glob.sync(buildRootPath)[0];
  232. fs.appendFileSync('./dist/index.html.gz',
  233. zlib.gzipSync(fs.readFileSync('./dist/index.html'),
  234. {
  235. chunckSize: 65536,
  236. level: zlib.constants.Z_BEST_COMPRESSION
  237. }));
  238. var getDirectories = function (src, callback) {
  239. var searchPath = path.posix.join(src, '/**/*(*.gz|favicon-32x32.png)');
  240. console.log(`Post build: Getting file list from ${searchPath}`);
  241. glob(searchPath, callback);
  242. };
  243. var cleanUpPath = path.posix.join(buildCRootPath, '/build/*.S');
  244. console.log(`Post build: Cleaning up previous builds in ${cleanUpPath}`);
  245. glob(cleanUpPath, function (err, list) {
  246. if (err) {
  247. console.error('Error', err);
  248. } else {
  249. list.forEach(fileName => {
  250. try {
  251. console.log(`Post build: Purging old binary file ${fileName} from C project.`);
  252. fs.unlinkSync(fileName)
  253. //file removed
  254. } catch (ferr) {
  255. console.error(ferr)
  256. }
  257. });
  258. }
  259. },
  260. 'afterEmit'
  261. );
  262. console.log('Generating C include files from webpack build output');
  263. getDirectories('./dist', function (err, list) {
  264. console.log(`Post build: found ${list.length} files. Relative path: ${wifiManagerPath}.`);
  265. if (err) {
  266. console.log('Error', err);
  267. } else {
  268. let exportDefHead =
  269. `/***********************************
  270. webpack_headers
  271. ${arguments[1]}
  272. ***********************************/
  273. #pragma once
  274. #include <inttypes.h>
  275. extern const char * resource_lookups[];
  276. extern const uint8_t * resource_map_start[];
  277. extern const uint8_t * resource_map_end[];`;
  278. let exportDef = '// Automatically generated. Do not edit manually!.\n' +
  279. '#include <inttypes.h>\n';
  280. let lookupDef = 'const char * resource_lookups[] = {\n';
  281. let lookupMapStart = 'const uint8_t * resource_map_start[] = {\n';
  282. let lookupMapEnd = 'const uint8_t * resource_map_end[] = {\n';
  283. let cMake='';
  284. list.forEach(foundFile => {
  285. let exportName = path.basename(foundFile).replace(/[\. \-]/gm, '_');
  286. //take the full path of the file and make it relative to the build directory
  287. let cmakeFileName = path.posix.relative(wifiManagerPath,glob.sync(path.resolve(foundFile))[0]);
  288. let httpRelativePath=path.posix.join('/',path.posix.relative('dist',foundFile));
  289. exportDef += `extern const uint8_t _${exportName}_start[] asm("_binary_${exportName}_start");\nextern const uint8_t _${exportName}_end[] asm("_binary_${exportName}_end");\n`;
  290. lookupDef += `\t"${httpRelativePath}",\n`;
  291. lookupMapStart += '\t_' + exportName + '_start,\n';
  292. lookupMapEnd += '\t_' + exportName + '_end,\n';
  293. cMake += `target_add_binary_data( __idf_wifi-manager ${cmakeFileName} BINARY)\n`;
  294. console.log(`Post build: adding cmake file reference to ${cmakeFileName} from C project, with web path ${httpRelativePath}.`);
  295. });
  296. lookupDef += '""\n};\n';
  297. lookupMapStart = lookupMapStart.substring(0, lookupMapStart.length - 2) + '\n};\n';
  298. lookupMapEnd = lookupMapEnd.substring(0, lookupMapEnd.length - 2) + '\n};\n';
  299. try {
  300. fs.writeFileSync('webapp.cmake', cMake);
  301. fs.writeFileSync('webpack.c', exportDef + lookupDef + lookupMapStart + lookupMapEnd);
  302. fs.writeFileSync('webpack.h', exportDefHead);
  303. //file written successfully
  304. } catch (e) {
  305. console.error(e);
  306. }
  307. }
  308. });
  309. console.log('Post build completed.');
  310. })
  311. ],
  312. optimization: {
  313. minimize: true,
  314. providedExports: true,
  315. usedExports: true,
  316. minimizer: [
  317. new TerserPlugin({
  318. terserOptions: {
  319. format: {
  320. comments: false,
  321. },
  322. },
  323. extractComments: false,
  324. // enable parallel running
  325. parallel: true,
  326. }),
  327. new HtmlMinimizerPlugin({
  328. minimizerOptions: {
  329. removeComments: true,
  330. removeOptionalTags: true,
  331. }
  332. }
  333. ),
  334. new CssMinimizerPlugin(),
  335. new ImageMinimizerPlugin({
  336. minimizer: {
  337. implementation: ImageMinimizerPlugin.imageminMinify,
  338. options: {
  339. // Lossless optimization with custom option
  340. // Feel free to experiment with options for better result for you
  341. plugins: [
  342. ["gifsicle", { interlaced: true }],
  343. ["jpegtran", { progressive: true }],
  344. ["optipng", { optimizationLevel: 5 }],
  345. // Svgo configuration here https://github.com/svg/svgo#configuration
  346. [
  347. "svgo",
  348. {
  349. plugins: [
  350. {
  351. name: 'preset-default',
  352. params: {
  353. overrides: {
  354. // customize default plugin options
  355. inlineStyles: {
  356. onlyMatchedOnce: false,
  357. },
  358. // or disable plugins
  359. removeDoctype: false,
  360. },
  361. },
  362. }
  363. ],
  364. },
  365. ],
  366. ],
  367. },
  368. },
  369. }),
  370. ],
  371. splitChunks: {
  372. cacheGroups: {
  373. vendor: {
  374. name: "node_vendors",
  375. test: /[\\/]node_modules[\\/]/,
  376. chunks: "all",
  377. }
  378. }
  379. }
  380. },
  381. // output: {
  382. // filename: "[name].js",
  383. // path: path.resolve(__dirname, "dist"),
  384. // publicPath: "",
  385. // },
  386. resolve: {
  387. extensions: ['.tsx', '.ts', '.js', '.ejs' ],
  388. },
  389. output: {
  390. path: path.resolve(__dirname, 'dist'),
  391. filename: './js/[name].[fullhash:6].bundle.js',
  392. clean: true
  393. },
  394. }
  395. )
  396. );