How does "import a library" actually works?

Tell us what’s happening:
I understand that importing something like this will give me access to the functions and basic resources I need to build react apps.

import React from 'react';

What I’m having trouble understanding now is a part of another React Project. The 4th usercase from the Markdown Project.

User Story #4: When I enter GitHub flavored markdown into the #editor element, the text is rendered as HTML in the #preview element as I type (HINT: You don’t need to parse Markdown yourself - you can import the Marked library for this: https://cdnjs.com/libraries/marked).

I researched a bit and found that I can import the library using this code available in the documentation.

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
        <script>
            document.getElementById('content').innerHTML =
            marked('# Marked in the browser\n\nRendered by **marked**.');
        </script>

But after I do this, what am I supposed to do to work with this library? It will give me other functions already made? As a begginer I feel a bit lost when working with this usercase. How do I know I sucessufully imported the library?

I saw that the documentation have this section about “The marked function”, but before going to use these functions I wanted to make sure that it was this what we - campers - were supposed to do. Searching the documentation and exploring these functions.

Your code so far

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36.

Challenge: Build a Markdown Previewer

Link to the challenge:

I’ve found something on stackoverflow that might be of some help to you for understanding what’s happening here.

If I’m not mistaken, using the <script> tag is going to import that file globally to everything within the project. As you begin to add things globally, you could run into variable and method names conflicting.

If you’re importing, this gives you the ability to keep the scale of that js file within that component itself, reducing the possibility of anything conflicting. Typically when I am working on a project I will use import over <script> so I can more easily encapsulate my code.

Hopefully this better explains how this works. There are different use cases for each.

2 Likes