Webpack-encore: How to import multiple js files?

Created on 9 Nov 2017  路  5Comments  路  Source: symfony/webpack-encore

node: 8.7.0
npm: 5.5.1
yarn : 1.2.1
webpack-encore: 0.17.0

Googled a lot with little or no success.
I need to PACK multiple separated js files into one app.js. How is that possible, using encore?

This is my webpack.config.js :

   ...
   .addEntry('app', './web/assets/js/main.js')
   ...

and This is main.js :

var $ = require('jquery');
window.$ = $;
window.jQuery = $;

importScripts(['./web/assets/vendor/semantic/semantic']);
importScripts(['./web/assets/js/tablesort']);

I need a functionality like @import, inside .scss files.

Most helpful comment

Hi @peyman-mohamadpour,

The paths are relative to the location of the file you add them in.

In your case:

require('../vendor/semantic/semantic.js');
require('./tablesort.js');

All 5 comments

Hey @peyman-mohamadpour!

This is exactly what the require keyword is for :). You're already packaging jquery.js into app.js by requiring it :). So, something like:

var $ = require('jquery');
window.$ = $;
window.jQuery = $;

require('./web/assets/vendor/semantic/semantic');
require['./web/assets/js/tablesort');

Those libraries may or may not return a value (the jquery module returns a value, for example) - so you may or may not need to set them to a variable. But by requiring them, they will be inside your final, built file.

Let us know if that helped! Cheers!

Using:

require('./web/assets/vendor/semantic/semantic');
require('./web/assets/js/tablesort');

This is what I get:

ERROR Failed to compile with 2 errors

These relative modules were not found:

* ./web/assets/js/tablesort in ./web/assets/js/main.js
* ./web/assets/vendor/semantic/semantic in ./web/assets/js/main.js

Hey @peyman-mohamadpour!

It looks like the file paths to those files are just incorrect :). Where do the tablesort.js and semantic.js files live? The require statement (much like @import) accepts a file path to the JavaScript file (but the .js suffix is optional). If you pass the wrong path, you'll get this error.

Cheers!

Could you please help me out of this?

semantic.js & tablesort.js location:

/Users/peyman/sites/newnarmafzam/web/assets/vendor/semantic/semantic.js
/Users/peyman/sites/newnarmafzam/web/assets/js/tablesort.js

main.js location:

/Users/peyman/sites/newnarmafzam/web/assets/js/main.js

webpack.config.js location (project root):

/Users/peyman/sites/newnarmafzam

What's the correct way of using require?

Hi @peyman-mohamadpour,

The paths are relative to the location of the file you add them in.

In your case:

require('../vendor/semantic/semantic.js');
require('./tablesort.js');
Was this page helpful?
0 / 5 - 0 ratings