Reputation: 1053
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
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.
Install browserify
globally using: npm install -g browserify
Use require()
to include your npm modules in your project.
const showdown = require('showdown');
Prepare a bundle for accessing require() function in your home.js
usnig browserify:
browserify js/home.js > bundle.js
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:
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