S
S
Sergey Sokolov2018-10-28 22:44:18
JavaScript
Sergey Sokolov, 2018-10-28 22:44:18

How to minify non-modular JS with webpack?

Scripts of third-party services were loaded on the page. Some of them are cut by adblockers, although they do not apply to advertising, so I want to include a local copy of those scripts in the assembly. Scripts are not modular and define global variables and functions.
How to configure webpack to just compile and minify multiple JS from a specific folder?
For example, the folder structure is:

myproject
|- package.json
|- webpack.config.js
|- /dist
  |- index.html
|- /src
  |- main.js
  |- /local_copies
    |- xd_connection.js
    |- rbadman-html5.min.js
    |- adman_init.js
    |- preroll.js

I just want to glue the scripts from /local_copiesand Uglify into a separate bundle, or include it in the general one.
In this case, none of the files is designed as a module. There's just an IIFE type, (function(w){ w.fastXDM = {...}})(window)or directly assigning a global object:
if (!window.VK) window.VK = {};
VK._Rpc = null;
VK._v = false;
VK._callbacks = {};
// ...

Change the content of these scripts, wrap them in a modular wrapper, etc. I don't want to - they will be regularly updated automatically from the CDN of those services. The list of created global variables is not exactly known and may change.
Connected scripts
https://vk.com/js/api/xd_connection.js?2
https://ad.mail.ru/static/admanhtml/rbadman-html5.min.js
https://vk.com/js/api/adman_init.js
https://js.appscentrum.com/scr/preroll.js
https://an.yandex.ru/system/context.js
https://mc.yandex.ru/metrika/watch.js

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2018-10-29
@sergiks

Solution: need special loader: script-loader
Install:
Use:
import exec from 'script-loader!./script.js';

0
0xD34F, 2018-10-28
@0xD34F

Everything is the same as with the rest of the files - just because the code is "non-modular" does not mean that you can not import. Just write something like:

import './local_copies/xd_connection.js';
import './local_copies/rbadman-html5.min.js';
// ну и т.д.

This is the so-called import for the sake of side effects.
Can be shortened by getting rid of the need to specify specific files using require.context :
const context = require.context('./local_copies', false, /\.js$/);
context.keys().forEach(key => context(key));

So they will all be in the same bundle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question