npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

js-to-js

v1.4.1

Published

ExpressJS template engine to render JavaScript from JavaScript to avoid inlined code and allow strict and safe Content-Security-Policy

Downloads

18

Readme

js-to-js

ExpressJS template engine to render JavaScript from JavaScript to avoid inlined code and allow strict and safe Content-Security-Policy.

Live demo at js-to-js.herokuapp.com

NPM

manpm Circle CI semantic-release

Read the following blog posts

Install

npm install --save js-to-js

Simple example

Inside your ExpressJS server use it as a template engine for 'js' files

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

var viewsFolder = join(__dirname, 'views');
app.set('views', viewsFolder);

var jsToJs = require('js-to-js');
app.engine('js', jsToJs);
app.locals.pretty = true; // render pretty output, don't minify for now

// when asked for 'js/analytics-config.js', render it dynamically
app.get('/js/analytics-config.js', function (req, res) {
  // use this for correct content-type -
  // Express will think it is text/html by default
  res.setHeader('content-type', 'application/javascript');
  // this path is WRT views folder
  res.render('js/analytics-config.js', {
    // use any run-time values, for example from config
    analyticsId: '4xx-xxxxx'
  });
});

The input object file

By default we expect the input views to be plain CommonJS modules exporting and object. The files are loaded using NodeJS require call. For example the views/js/analytics-config.js file might be just an object with single property.

module.exports = {
  analyticsId: 'default-id'
};

The CommonJS format is simple to use and test.

The rendered script file

The rendered file will have a single variable declared with the value being the object from the input file, but the values replaced / extended using dynamic values.

The name of the variable will be the kebab case of the base name of the requested file. For example if the input file is views/js/analytics-config.js and rendered using options

{
  analyticsId: '0123456',
  user: '[email protected]',
  UUID: 'abcd012345'
}

then the produced JavaScript file will contain only the following code

var analyticsConfig = {
  analyticsId: '0123456'
};

Limiting the keys to only the ones already in the input file is done for modularity.

Wrapping a function example

If you need to inject values into a 3rd party script, like Google Analytics, export a function that expects options argument. The function will be wrapped in an IIFE with actual arguments passed in.

// analytics.js in the views folders
module.exports = function (options) {
  initAnalytics(options.userId);
};

You route can be setup exactly like before

var userId = 'xx-yy-bb';
app.get('/js/analytics.js', function (req, res) {
  res.setHeader('content-type', 'application/javascript');
  res.render('analytics.js', {
    userId: userId
  });
});

At runtime it will be rendered back to the user something like this

(function (options) {
  initAnalytics(options.userId);
}({ userId: 'xx-yy-bb' }));

Using as middleware

Sometimes you have a simple object with settings you just want to send to the client, but generate a script variable. Just use js-to-js as middleware generator.

var jsToJs = require('js-to-js');
app.get('/js/demo-config-object.js',
  jsToJs('demoConfig', { foo: 42, bar: 21 }));

Whenever the client requests /js/demo-config-object.js the server will respond with dynamically generated script with the following contents

var demoConfig = { foo: 42, bar: 21};

Working example / demo

This repository bahmutov/js-to-js contains fully working example in the demo subfolder. You can run it locally using

git clone [email protected]:bahmutov/js-to-js.git
cd js-to-js/demo
npm install
node index.js
open http://localhost:3000/index.html

You can also see it deployed at js-to-js.herokuapp.com.

demo

Small print

Author: Gleb Bahmutov © 2015

License: MIT - do anything with the code, but don't blame me if it does not work.

Spread the word: tweet, star on github, etc.

Support: if you find any problems with this module, email / tweet / open issue on Github

MIT License

Copyright (c) 2015 Gleb Bahmutov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.