jeremy.jass's avatar

Accessing Compiled Javascript Assets from Blade Templates

Trying to access the "d3" library, but pulling it in through npm and adding it as a dependency to a compiled file that is already bundling together some similar functionality. To the asset js file I added the line:

var d3 = require("d3");

and judging by the size increase in the compiled js file it looks like it pulls in successfully. Now I'm sure I could do "d3. ..." stuff in the asset js file, but what I want to do is use d3 in blocks down in later blade templates.

If I pull in a d3 file "the old way" by adding a "" line I can use d3 in script blocks later on the page.

If I pull in the compiled file by adding a "" line I think the code is there, but d3 is not defined.

0 likes
2 replies
jeremy.jass's avatar

@ejdelmonico, that stack blade directive is really neat, but a large part of my goal was to reduce the number of file requests to load the page by squishing everything down into one file using the webpack compiler.

It was late last night, and looking at it this afternoon with fresh eyes I think I've figured out how to solve my issue. Looking into the /resources/assets/js/bootstrap.js file supplied with Laravel 5.4 and they way they bind JQuery to '$' and 'JQuery', I was able to do the same thing binding the d3 library to 'd3'. I had seen this before, but missed that it was a "window" not a "Window" with a capital 'W'. 'Window.d3' is also a thing, but doesn't let you call "d3.doStuff" like you would with normal import.

After installing the 'd3' package through npm, in the source javascript file.

window.d3 = require('d3');

Then on any pages that include the compiled js file you will have access to the d3 modules.

Please or to participate in this conversation.