#StackBounty: #reactjs #caching #webpack #updates #whatsapp How does whatsappweb deliver updates?

Bounty: 50

I’m wondering how does whatsappweb deliver updates?
Do you ever notice a left green card appearing sometimes and asking you to click in a link to refresh page and run the new whatsappweb fresh code updated.

I’m almost sure they use webpack, service workers etc.

Chances are that you already had cache problems using webpack where even refreshing page it remains cached.
So how does whatsappweb solved this issue with a single refresh link?


Get this bounty!!!

#StackBounty: #javascript #typescript #webpack Webpack 4.44.2 loads modules statically instead of requested dynamic loading

Bounty: 50

Project

enter image description here

FrontendLogicPreProcessingTesting.ts

(function executeApplication(): void {
  const loadDataButton: HTMLElement | null = document.getElementById("LoadDataButton");
  if (loadDataButton !== null) {
    loadDataButton.addEventListener("click", async () => {
      const loadedValue: string = await loadDataOnDemand();
      console.log(loadedValue);
    });
  }
})();


async function loadDataOnDemand(): Promise<string> {

  const MODULE: { default: string; DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE: string; } =
      await import("./DynamicLoadingTesting/TypeScriptModuleForDynamicLoading");
  return MODULE.DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE;
}

TypeScriptModuleForDynamicLoading.ts

const DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE_BY_DEFAULT: string =
    'I was dynamically loaded from TS module by default!';
export default DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE_BY_DEFAULT;

export const DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE: string =
    'I was dynamically loaded from TS module!';

It seems like button’s click event handler works correclty:

enter image description here

But the module TypeScriptModuleForDynamicLoading.ts has not been loaded dynamically. It has been bundled to FrontendLogicPreProcessingTesting.js:

enter image description here

My Webpack config:

{

  name: 'FrontendLogicPreProcessingTesting',
  context: 'D:\XXXXX\00-Source\FrontendLogicPreProcessingTesting',
  target: 'web',

  entry: {
    FrontendLogicPreProcessingTesting: 'D:/IntelliJ IDEA/InHouseDevelopment/Hikari-Monorepo/ProjectsForFunctionalTesting/ProjectBuildingCommonTest/00-Source/FrontendLogicPreProcessingTesting/FrontendLogicPreProcessingTesting.ts'
  },

  output: {
    path: 'D:\XXXXX\01-DevelopmentBuild\FrontendLogicPreProcessingTesting',
    publicPath: './',
    filename: '[name].js',
    chunkFilename: 'load_on_demand/partial__[id].js'
  },

  mode: 'development',
  watch: true,
  devtool: 'eval',
  module: {
    rules: [/* ... */]
  },
  resolve: {
    extensions: [ '.mjs', '.js', '.ts' ],
    alias: { vue: 'vue/dist/vue.common.js' }
  },
  optimization: { minimize: false, noEmitOnErrors: false }
}

My public path is './' because I need the dynamical loading works without development server, just by opening the HTML file. I used relative public path before, but now there is the another error somewhere.


Get this bounty!!!

#StackBounty: #javascript #reactjs #webpack #refactoring How can I refactor by moving files in a JavaScript project and have references…

Bounty: 50

General tips are welcome. My specific situation is a React app, compiled with WebPack, with lots of files. If I want to move a file or folder within the project, is there a good way to do this such that references, such as import & require statements, update automatically?

Bonus points for solutions using Atom or VSCode.

NPM scripts will also work. Thanks.


Get this bounty!!!

#StackBounty: #npm #webpack #imagemin npm run watch Error in Cannot read property of 'map' undefined

Bounty: 50

Problem:
Running the command npm run watch throws and error

54% building 35/41 modules 6 active /app/docroot/themes/custom/mytheme/node_modules/css-loader/index.js??ref--10-2!/app/docroot/themes/custom/mytheme/node_modules/postcss-loader/src/index.js??postcss5!/app/docroot/themes
 ERROR  Failed to compile with 1 errors          1:25:50 AM

 error 

Cannot read property 'map' of undefined

 15 assets

ERROR in Cannot read property 'map' of undefined
[Browsersync] Proxying: https://ps.lndo.site

The Error happens only when the following code is included in my webpack.mix.js file:

mix.imagemin({
  patterns: [{
    from: '**/*.{png,gif,jpg,jpeg,svg}',
    to: 'images/',
    context: 'src/images/'
  }, {
    from: '**/*.{png,gif,jpg,jpeg,svg}',
    to: 'images/',
    context: 'src/components/'
  }]
  });

Removing the above snippet removes the error but the previous developers on this project had this for a reason.

I recently updated due to security vulnerabilities and managed to debug a different issue that Copy Plugin introduced a breaking change (already updated in the code above). However I am unsure that I have all of the configuration correct.

This I have tried:
From the command line

rm -rf node_modules
rm package.lock
npm cache clean --force
npm install

These are the packages in package.json current as of August 27, 2020

"devDependencies": {
    "bootstrap": "^4.3.1",
    "browser-sync": "^2.26.12",
    "browser-sync-webpack-plugin": "^2.2.2",
    "copy-webpack-plugin": "^6.0.3",
    "cross-env": "^7.0.2",
    "husky": "^4.2.5",
    "imagemin-webpack-plugin": "^2.4.2",
    "jquery": "^3.5.1",
    "laravel-mix": "^5.0.4",
    "laravel-mix-imagemin": "^1.0.3",
    "popper.js": "^1.16.1",
    "pretty-quick": "^2.0.1",
    "resolve-url-loader": "^3.1.1",
    "sass": "^1.26.10",
    "sass-loader": "^8.0.2",
    "vue-template-compiler": "^2.6.11"
  },
"dependencies": {
    "throttle-debounce": "^2.3.0"
  }

The packages updated were the following

    "browser-sync": "^2.26.7",
    "copy-webpack-plugin": "^5.1.1",
    "husky": "^4.2.3",
    "jquery": "^3.5.0",
    "sass": "^1.26.3",

    "throttle-debounce": "^2.1.0"


Get this bounty!!!

#StackBounty: #javascript #webpack #vmware-clarity webpack PurgeCSS webpack Plugin not working as expected

Bounty: 50

I want to purge unused CSS from the Clarity UI CSS file, in a setup using webpack and purgecss-webpack-plugin.
However, while the size of the CSS file is reduced from 565kB to 172kB, it should be reduced to 0kB since I don’t use any of it. If I do the same thing using Bootstrap, the filesize is reduced to 1kB.

Why is that behaviour and is there a fix?

My folder structure is as follows:

|-dist  
|  
|-node_modules  
|  
|-src  
  |--index.js  
|  
|.babelrc  
|package.json  
|webpack.config.js 

My package.json:

{
  "name": "webpack-clarity",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "start": "node ./index.js",
    "build": "webpack"
  },
  "dependencies": {
    "@clr/ui": "^4.0.0",
    "bootstrap": "^4.5.2"
  },
  "devDependencies": {
    "@babel/core": "^7.10.4",
    "@babel/preset-env": "^7.10.4",
    "babel-loader": "^8.1.0",
    "css-loader": "^3.6.0",
    "glob": "^7.1.6",
    "html-webpack-plugin": "^4.3.0",
    "mini-css-extract-plugin": "^0.9.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "purgecss-webpack-plugin": "^2.3.0",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12"
  }
}    

webpack.config.js

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const glob = require("glob");
const PurgeCSSPlugin = require("purgecss-webpack-plugin");

module.exports = {
  mode: "production",
  entry: "./src/index.js",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
  },
  optimization: {
    minimizer: [new OptimizeCssAssetsPlugin(), new TerserPlugin()],
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: ["babel-loader"],
      },
      {
        test: /.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: "[name].css" }),
    new PurgeCSSPlugin({
      paths: glob.sync("./src/**/*.js", { nodir: true }),
    }),
  ],
};

.babelrc

{
  "presets": [
    [   
      "@babel/preset-env",
      {"modules": false}
    ]
  ]
}

index.js

import "../node_modules/@clr/ui/clr-ui.min.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";


Get this bounty!!!

#StackBounty: #javascript #webpack #bundle #gatsby #tree-shaking Code-splitting separate exports from a package to different bundles

Bounty: 500

I have a Gatsby site that consumes a number of packages. One of those packages is published from our monorepo: @example/forms. That package contains a number of named exports, one for each form component that we use on our site. There are quite a large number of forms and some are relatively complex multistep forms of a non-trivial size.

Currently, Gatsby/Webpack does a good job of treeshaking, and does produce a large number of bundles, some common bundles and one for each page of the site, containing any local assets or components that are only used on that page. However, all the components from @example/forms are being added to the commons bundle, despite the fact that most are used on only a single page. This is causing unnecessary bloat of the commons bundle which is loaded on every page.

If feels like it should be possible for the individual components within @example/forms to be split out into the page-specific bundles, but I’m not sure if I’m hoping for too much. For example, if Form A is only used on page 4, I’d like Form A to only be added to the bundle for page 4.

Is this something that is supported, and if so, what could be preventing this from happening.

@example/forms is transpiled with ES6 exports left intact, and sideEffects is set to false in its package.json.

Its main file is index.js which (re)exports all the form components from their own files as separate named exports:

export {default as FormA} from './forms/formA'
export {default as FormB} from './forms/formB'
...

Another thing that might be relevant is that all the exports from @example/forms are used within the Gatsby site, just on separate pages. It appears that perhaps tree-shaking cannot be used across bundles, i.e. tree shaking is performed first, then what is left is split into bundles. Using that logic, @example/forms would have been used on multiple pages and would be moved to commons. However this is definitely not optimal, and hopefully isn’t what is happening.


Get this bounty!!!

#StackBounty: #reactjs #webpack #storybook #react-proptypes How to enable prop-types in production for a React Storybook for the Docs a…

Bounty: 50

By default prop-types do not run in production for a react app. I realize this is a good thing to improve performance. However, we have a Storybook that we have built and are deploying it to a static site. Storybook has an addon called Docs that detects the prop-types for components and creates a table of the prop-types for easy to read documentation.

When running the storybook locally, everything works perfectly. The prop-types are detected and this table is generated.

SpinningLoader.propTypes = {
  color: PropTypes.string,
  size: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};

enter image description here

However, since prop-types are disabled in production by default. They cannot be detected when the storybook is deployed to a static site.

enter image description here

Is there a way to enable prop-types in production? Or some other workaround?


Get this bounty!!!

#StackBounty: #reactjs #typescript #webpack #visual-studio-code #gatsby Typescript & Gatsby: Development bundle cannot resolve path…

Bounty: 50

I have a bunch of imports like import Navi from 'components/Navi'

These have a red error line under the components/Navi part until I add this to my tsconfig.json

"baseUrl": "./",
"paths": {
  "components/*": ["src/components/*"],
  "layouts/*": ["src/layouts/*"],
  "pages/*": ["src/pages/*"],
  "templates/*": ["src/templates/*"],
  "scss/*": ["src/scss/*"],
  "types": ["src/types"]
}

At which point the error goes away. When I try to build my develop bundle through running gatsby develop everything looks fine until this appears ⠹ Building development bundle

Which is followed shortly by lots of statements like Can't resolve 'components/Navi' in '~/src/components'

And these errors only go away when I specify a relative path like import Navi from '../Navi'


As a side note, I also can’t do import {MyType} from 'types' with a structure of

src
    -> types
        -> index.ts

It gives an error with a red line under the word 'types' which states Cannot find module 'types'.ts(2307) And I must change the import to import {Issue} from 'types/index'


I already tried running gatsby clean and deleting node_modules


Get this bounty!!!

#StackBounty: #webpack #bootstrap-4 #webpack-4 #svelte #css-purge Unable To Strip Unused Bootstrap CSS Using Webpack Config

Bounty: 100

Using the configuration below, I’m able to create a single HTML file containing all my code correctly, but lots of unused bootstrap classes in there.

Please note that I’m customising Bootstrap by importing SCSS files from node_modules into a main.scss file in code.

Where am I going wrong?

const path = require('path');
const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const {
  scss
} = require('svelte-preprocess');
const Dotenv = require('dotenv-webpack');
const PurgecssPlugin = require('purgecss-webpack-plugin');
const glob = require('glob');

const prod = process.env.NODE_ENV === 'production';

module.exports = {
  module: {
    rules: [{
        test: /.svelte$/,
        exclude: /node_modules/,
        loader: 'svelte-loader',
        options: {
          emitCss: true,
          hotReload: false,
          preprocess: require('svelte-preprocess')([scss()]),
        },
      },
      {
        test: /.(sa|sc|c)ss$/,
        exclude: /node_modules/,
        use: [{
            loader: prod ? MiniCssExtractPlugin.loader : 'style-loader', // inject CSS to page
          },
          {
            loader: 'css-loader', // translates CSS into CommonJS modules
          },
          {
            loader: 'postcss-loader', // Run post css actions
            options: {
              plugins: function() {
                // post css plugins, can be exported to postcss.config.js
                return [require('precss'), require('autoprefixer')];
              },
            },
          },
          {
            loader: 'sass-loader', // compiles Sass to CSS
          },
        ],
      },
    ],
  },
  resolve: {
    alias: {
      svelte: path.resolve('../../node_modules', 'svelte'),
    },
    extensions: ['.mjs', '.js', '.svelte'],
    mainFields: ['svelte', 'browser', 'module', 'main'],
  },
  optimization: {
    minimizer: [
      new OptimizeCssAssetsPlugin({
        cssProcessorOptions: {
          map: {
            inline: false
          }
        },
      }),
      new TerserPlugin(),
    ],
  },
  plugins: [
    new Dotenv(),
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      minify: prod ?
        {
          collapseWhitespace: true,
          removeComments: true,
          removeRedundantAttributes: true,
          removeScriptTypeAttributes: true,
          removeStyleLinkTypeAttributes: true,
          useShortDoctype: true,
        } :
        false,
      template: 'index.html',
      inlineSource: '.(js|css)$', // embed all javascript and css inline
    }),
    new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin),
    new PurgecssPlugin({
      paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, {
        nodir: true
      }),
    }),
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Here’s the single and only SCSS file I’m using in the project; it’s imported in index.js and serves as the only styling source for the whole project:

//colors
$primary: #123099;

//body
$body-bg: #3123b7;

// Required
@import '~bootstrap/scss/functions';
@import '~bootstrap/scss/variables';
@import '~bootstrap/scss/mixins/border-radius';
@import '~bootstrap/scss/mixins/buttons';
@import '~bootstrap/scss/mixins/gradients';
@import '~bootstrap/scss/mixins/list-group';
@import '~bootstrap/scss/mixins/background-variant';
@import '~bootstrap/scss/mixins/forms';
@import '~bootstrap/scss/mixins/grid';
@import '~bootstrap/scss/mixins/grid-framework';
@import '~bootstrap/scss/mixins/box-shadow';
@import '~bootstrap/scss/mixins/transition';
@import '~bootstrap/scss/mixins/hover';
@import '~bootstrap/scss/mixins/size';
@import '~bootstrap/scss/mixins/breakpoints';
@import '~bootstrap/scss/mixins/text-truncate';
@import '~bootstrap/scss/mixins/deprecate';
@import '~bootstrap/scss/mixins/text-hide';
@import '~bootstrap/scss/mixins/text-emphasis';
@import '~bootstrap/scss/vendor/rfs';
@import '~bootstrap/scss/reboot';

// Optional
@import '~bootstrap/scss/utilities/spacing';
@import '~bootstrap/scss/utilities/sizing';
@import '~bootstrap/scss/utilities/flex';
@import '~bootstrap/scss/utilities/borders';
@import '~bootstrap/scss/utilities/text';
@import '~bootstrap/scss/utilities/background';
@import '~bootstrap/scss/utilities/shadows';
@import '~bootstrap/scss/utilities/display';
@import '~bootstrap/scss/utilities/position';
@import '~bootstrap/scss/grid';
@import '~bootstrap/scss/card';
@import '~bootstrap/scss/forms';
@import '~bootstrap/scss/buttons';
@import '~bootstrap/scss/list-group';
@import '~bootstrap/scss/custom-forms';
@import '~bootstrap/scss/spinners';


Get this bounty!!!

#StackBounty: #javascript #webpack #babeljs #es6-modules How to export multiple ES6 modules from one NPM package

Bounty: 50

I’ve built a relatively small NPM package consisting of roughly 5 different ES6 classes contained in one file each, they all look pretty much like this:

export default class MyClass {
    // ...
}

I’ve then setup an entry point for my package that looks like this:

export { default as MyClass } from './my-class.js';
export { default as MyOtherClass } from './my-other-class.js';

I’ve then run the entry point through webpack and babel ending up with a transpiled and minified index.js

Installing and importing the package works fine, but when I do the following from my client code:

import { MyClass } from 'my-package';

It doesn’t just import “MyClass” it imports the entire file including all dependencies of every class (some of my classes have huge dependencies).

I figured this is how webpack works when you try to import parts of an already bundled package? So I set up my local webpack config to run node_modules/my-package through babel too and then tried:

import { MyClass } from 'my-package/src/index.js';

But even this imports every single class exported by index.js. The only thing that seems to work the way I want is if I do:

import MyClass from 'my-package/src/my-class.js';

But I’d much rather:

  1. Be able to import the transpiled and minified file so that I don’t have to tell webpack to run babel inside node_modules and
  2. Be able to import each individual class directly from my entry point instead of having to enter the path to each file

What’s the best practice here? How do others achieve similar setups? I’ve noticed GlideJS has an ESM version of its package which allows you to import only the things you need without having to run babel through it for example.

The package in question: https://github.com/powerbuoy/sleek-ui

webpack.config.js

const path = require('path');

module.exports = {
    entry: {
        'sleek-ui': './src/js/sleek-ui.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
        library: 'sleek-ui', // NOTE: Before adding this and libraryTarget I got errors saying "MyClass() is not a constructor" for some reason...
        libraryTarget: 'umd'
    },
    module: {
        rules: [
            {
                test: /.js$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env']
                        }
                    }
                ]
            }
        ]
    }
};

package.json

  "name": "sleek-ui",
  "version": "1.0.0",
  "description": "Lightweight SASS and JS library for common UI elements",
  "main": "dist/sleek-ui.js",
  "sideEffects": false, // NOTE: Added this from Abhishek's article but it changed nothing for me :/
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack --mode production"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/powerbuoy/sleek-ui.git"
  },
  "author": "Andreas Lagerkvist",
  "license": "GPL-2.0-or-later",
  "bugs": {
    "url": "https://github.com/powerbuoy/sleek-ui/issues"
  },
  "homepage": "https://github.com/powerbuoy/sleek-ui#readme",
  "devDependencies": {
    "@babel/core": "^7.8.6",
    "@babel/preset-env": "^7.8.6",
    "babel-loader": "^8.0.6",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.11"
  },
  "dependencies": {
    "@glidejs/glide": "^3.4.1",
    "normalize.css": "^8.0.1"
  }
}


Get this bounty!!!