2
0

webpack.config.js 14 KB

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