ryantuck
ryantuck

Reputation: 6634

Add a node_module as a javascript src in html

Seems crazy that this isn't as easy as it should be.

My file structure:

node_modules/
public/
 -- css/
 -- js/
 -- index.html

In index.html, I try to load a file in a node_module, like so:

<script src="../node_modules/angular-ui-sortable/src/sortable.js"></script>

But, this doesn't work. My error:

SyntaxError: Unexpected Token '<' 

I check the resources, and sortable.js is being loaded with the content of index.html. I've seen this issue when the designated javascript file can't be found.

Is this just some wonky issue with nodeJS? Is there some black magic needed to simply load a javascript file into html?

Upvotes: 1

Views: 3620

Answers (2)

Yossi Hohashvili
Yossi Hohashvili

Reputation: 1

I tried it out and this fix worked for me:

in you app.js in node add this:

app.use('/node_modules',express.static(path.join(__dirname , 'node_modules')));

and in your index.html add this:

<script src="node_modules/<packagename>/<filename>.js"></script>

If you worry about importing unwanted packages from node_models folders you could specify the routing to a specific folder of the desired package. Hope this helps.

Upvotes: 0

generalhenry
generalhenry

Reputation: 17319

I suspect you're doing something like this:

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public');

Which would produce the kind of result your seeing. Suggested fix:

add

app.use(express.static(__dirname + '/node_modules');

and change the url to

<script src="/node_modules/angular-ui-sortable/src/sortable.js"></script>

Upvotes: 3

Related Questions