Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bundle legacy js files with webpack?

Suppose I have two files

a.js:

alert("hello from a.js");

b.js

alert("hello from b.js");

is there any way to bundle them with WebPack so that

  1. I get both alerts synchronously as soon as bundle is loaded
  2. alerts should be in the same order as declared "hello from a" and then "hello from b"
like image 416
Alex Ilyin Avatar asked Apr 28 '16 15:04

Alex Ilyin


People also ask

How do I use Webpack to bundle JavaScript?

You can bundle your JavaScript using the CLI command by providing an entry file and output path. Webpack will automatically resolve all dependencies from import and require and bundle them into a single output together with your app’s script. But that’s just the bare minimum it can do.

How do I create a Webpack config file?

Create a webpack.config.js file in the project root: And add the following code: And change the npm script to the following: In webpack.config.js we’re exporting a configuration object, which specifies the entry point, the mode webpack should run in (more on that later), and the output location of the bundle.

What is Webpack and why should I Care?

This is one of the most interesting features of Webpack. It allows you to preprocess files as they are loaded and since everything is a module in Webpack (yes PNG, Less, Jade, and CSS files are all modules) you can easily load them using specific Webpack loaders.

How to link a bundled JavaScript file in HTML?

We can link our bundled JavaScript file in our HTML, like so: When we view the HTML file, we should get the same result. This method encourages modular JavaScript and different JavaScript engineers can work on different aspects of the same project. Now, let’s understand what the above Webpack command did.


3 Answers

Webpack natively supports CommonJS ( require / import ) and AMD style, and since yours are not falling into those categories, I believe you should look at the shimming modules section

https://github.com/webpack/docs/wiki/shimming-modules

This is from their header

In some cases webpack cannot parse some file, because it has a unsupported module format or isn't even in a module format. Therefore you have many options to convert the file into a module.

like image 153
R.R Avatar answered Oct 19 '22 11:10

R.R


For anyone else that comes looking, the new (webpack 4+) link to the docs on shimming is here: https://webpack.js.org/guides/shimming/

like image 2
Tom Davies Avatar answered Oct 19 '22 13:10

Tom Davies


For me personally, this webpack plugin was most helpful and headache free: https://www.npmjs.com/package/webpack-merge-and-include-globally

like image 1
okliv Avatar answered Oct 19 '22 13:10

okliv