Import js script in js, follow DRY


#1

Hi,

I have multiple node glitch’s running that have some of the same functions in their code. For example there is one function I have copied and pasted into every glitch. I would prefer to follow DRY (Don’t repeat yourself) and instead, in my js file i’d like to import the js script that contains the function. I would like to host this js script on glitch also. Is this possible?


#2

You can copy and paste the content of the JS file into one on Glitch, or import the file using GitHub import or using wget from the console. Once on Glitch, you can then use Express to create a route to serve the JS file.


#3

Sorry, I don’t think I explained myself well. I would like to host a .js file in one glitch - and use this file in 10 other glitches I have made. Is this possible?

Usually you would import the .js file from it’s URL. But I can’t find the URL of .js files hosted on glitch.

Tom


#4

if the file in your repo is in the “public” folder, then it can be publicly accessed via project-name.glitch.me/filename.js (without the public). However this will allow everyone in the world to see it…


#5

Perhaps a worked example will help. So in a default ‘node-app’ new project on Glitch like https://glitch.com/edit/#!/dog-ophthalmologist, because we’ve told Express to serve the public folder as a static folder and we have put client.js in it, we can access client.js at https://dog-ophthalmologist.glitch.me/client.js. You could do the same to use JavaScript files between projects.


#6

Ah perfect solution! Will this have to startup if the app closes down though?


#7

Yes, all apps on Glitch function like that unless forced awake.


#8

Thanks so much Gareth!


#9

Another possibility is to publish your code as an npm package, and then include it in package.json in the projects that use it.


#10

That’s a ripper idea too!


#11

Trying to avoid publishing as an npm package, but there doesn’t seem like a decent way to import js into a js file otherwise. My project is a node app built on express, so I don’t have a front facing html page to import the script.


#12

If you don’t want to use up a package name, you can publish it under your own scope on npm (@yourusername/package-name).