Using express-babelify-middleware with FeathersJS

101 views Asked by At

I am trying to use express-babelify-middleware
with FeathersJS and the error shows up in the browser console:

ReferenceError: main_run is not defined

I take this to mean that babelify is not working or I am using it incorrectly as main_run is in the global namespace of the src in my html file.
Here is my setup using the structure from feathers generate:

public/index.html:

<!DOCTYPE html>
<html>
<head>
<title>babelify test</title>

<script src="main.js"></script>
<script>
main_run()
</script>
</head><body>
<p>Testing feathers with babelify</p>
</body></html>

public/main.js

const external_module = require('./test')

function main_run(){
external_module()
}

public/test.js

module.exports = function(){
console.log("Hello world for an external module")
}

among the .uses of src/app.js:

...

const babelify = require('express-babelify-middleware')

...

app.use(compress())
  .options('*', cors())
  .use(cors())
//the line that is not working:
.use('/main.js', babelify( path.join(app.get('public'), 'main.js') ))

  .use(favicon( path.join(app.get('public'), 'favicon.ico') ))
  .use('/', serveStatic( app.get('public') ))

When I visit localhost:3030/main.js I can see the file, but the functions look to be in a function of their own, so I don't know how to get into that function.

1

There are 1 answers

0
Brandon Keith Biggs On

Silly problem, one can't access browserified code in the html file that calls it. So public/index.html can't access main_run unless it is attached to the window object. There is a similar question
here.
Other than that, my code works perfectly.
In main.js place the following code at the bottom:

window.main_run = main_run

Then in index.html replace the main_run() line with:

window.main_run()

This will write the contents of test.js to the console.