Drafts Action Directory

Require NPM Module

Posted by @galtenberg, Last updated: 2018-07-04 14:32:46 UTC

// Require NPM Module (via Unpkg)

// Include this action before your script
// Then in your script, call require() with a common npm package
// (Not all npm packages are supported)
// Try lines like those below
// Works great with “Eval Draft” action

////

removeBasic = require(‘remove-words’)
removeBasic(“Today is sunny so we are going to go swimming at the seaside”)

////

require(‘hashids’)
const hashids = new Hashids(‘my-app’, 0, ‘abcdefgh12345678’)
hashids.encode(13579)

Install

Steps

  • script

    const debug = false
    
    // Claim the require function, load from unpkg
    // Allows internal, recursive calls to require
    // Won't work for all packages
    // - those that contain relative requires like '../file.json'
    
    const require = (moduleName) => {
    
      const response = HTTP.create().request({
        "url": `https://unpkg.com/${moduleName}`
      })
      
      if (response.responseText.startsWith("Cannot find package")) {
        alert(`Cannot find package at unpkg.com/${moduleName}`)
        return
      }
      
      // In case package attempts to set module.exports
      let module = {}
    
      eval(response.responseText)
        
      if (debug) { 
        console.log(JSON.stringify(response))
        console.log(JSON.stringify(this))
      }
    
      if (module.exports) 
        return module.exports   
    }
    
    // In case package gets cute with node assumptions
    const process = {
      env: {
        NODE_ENV: undefined
      }
    }

Options

  • After Success Nothing
    Notification Error
    Log Level Info

Comments

Actions available in the Action Directory are uploaded by community members. Use appropriate caution reviewing downloaded actions before use.