netlemon
netlemon

Reputation: 1053

Import module from npm to javascript file

I am trying to import showdown module in my home.js file.

The GitHub installation guide tells me to run npm install showdown and presents a simple example of using the module, as such:

var converter = new showdown.Converter(),
    text      = '# hello, markdown!',
    html      = converter.makeHtml(text);

I have installed the module using that command, but now I m not sure how to use this module inside my home.js situated under app/static/js path. I tried using require but it s not a solution since

it does not exist in the browser/client-side JavaScript.

Project Tree

├── app
│   ├── __init__.py
│   ├── routes.py
│   └── static
│       ├── js
│       │   └── home.js
│       └── styles
│           ├── main.css
│           └── normalize.css
├── config.py
├── package-lock.json
├── package.json
├── run.py
└── node_modules

Javascript file home.js


const textEditor = document.querySelector('.text-editor')
const preview = document.querySelector('.preview')
var converter = new showdown.Converter() // <- error fires here

console.log('text-editor', textEditor)
console.log('preview', preview)

textEditor.addEventListener('keyup', event=>{
    const {value} = event.target;

    const html = converter.makeHtml(value)

    preview.innerHtml = html
});

Question: How do I import this showdown inside my index.js so that I can be able to use every function of the module?

Upvotes: 1

Views: 458

Answers (1)

Dhruv Shah
Dhruv Shah

Reputation: 1651

You can use Browserify for this. It allows you to use require() for requiring node_modules.

Here are the steps in which you can use the showdown npm package in your project.

  1. Install browserify globally using: npm install -g browserify

  2. Use require() to include your npm modules in your project.

    const showdown = require('showdown');

  3. Prepare a bundle for accessing require() function in your home.js usnig browserify:

    browserify js/home.js > bundle.js

  4. Include the bundle.js file created in your code using the script tag.

    <script src="bundle.js"></script>

Here are some resources that explain how to use browserify in more detail:

  1. https://medium.com/jeremy-keeshin/hello-world-for-javascript-with-npm-modules-in-the-browser-6020f82d1072

  2. https://github.com/browserify/browserify#usage

Additionally, this article also explains well how to choose the tool for compiling your front-end applications based on your requirements. And it contains detailed information about how to use browserify

Upvotes: 1

Related Questions