This middleware was created to directly inject javascript files into <script>
tags via templates rendered from the Express JS framework.
Installation
npm install express-script-injector --save
Usage
var injector = ; var options = path: __dirname + '/scripts' // **required** path to your scripts folder (default: undefined) debug: false // *optional* Enable debugging to console (default: false) script: 'index.js' // *optional* Script to inject (default: index.js) enableCache: false // *optional* Cache previously loaded scripts to RAM (default: false) useRoute: false // *optional* If set to true, it will attempt to match the root route and load a script with the same name. (default: false) app; // OR router;
The injector middleware will then expose the content of a js file inside req._script, so that you can render it with a template (see example below)
Example
This example shows how it might be used with an express application using handlebars templating.
var express = exphbs = injector = ; var app = ; // Apply the injector middleware (note: it could also just be added to a router instead)app; app;app; app; app;
Then somewhere in your home.hbs file:
{{{injectedScript}}}
Router Example
var router = inject = ; router; router; moduleexports = router;
This outputs the js in a
<script>
tag with the id of "injector-" + the file name
Options
Name | Description | Default |
---|---|---|
path(required!) | path to your scripts folder | undefined |
debug | Enable debugging to console | false |
script | file to inject | index.js |
enableCache | Cache previously loaded scripts to RAM | false |
useRoute | Experimental: If set to true, it will attempt to match the root route and load a script with the same name. If it does not find a file, it "falls back" load the script option. | false |