skip to Main Content

Hi there i am trying to play around with packages and installed the date-fns package but cant seem to use it, i have a feeling its because of how my folders are set up but dont know the right way, where should my node modules folder and json package folders be in relation to my folder with all the projects im working on be? my projects are in a folder called projects on my desktop
enter image description here

2

Answers


  1. Adam.
    You need to set the structure of your project as below.

    enter image description here

    Hope this can help you.
    Thanks.

    Login or Signup to reply.
  2. The basic steps to install a package in a project that uses npm, if you’re starting from scratch, is to prepare the environment first before using the package. Here’s what I do:

    1. Make sure you have node and npm installed in your local terminal.
    2. Run npm init to initiate the package.json
    3. Choose a bundler library to compile your code. For this example, I choose vite. Run npm install -D vite
    4. Install the library you wanted, like date-fns. Run npm install date-fns
    5. Create a simple HTML file that loads the main.js script. (We’ll create the script after this step)
    // index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Vite App</title>
      </head>
      <body>
        <div id="app"></div>
        <script type="module" src="/main.js"></script>
      </body>
    </html>
    
    1. Create a JS file main.js, then use the date-fns there to print the date into the HTML.
    // main.js
    import { format } from 'date-fns'
    
    const today = format(new Date(), "'Today is a' eeee")
    document.getElementById('app').innerHTML = today;
    
    1. Update package.json to run the vite:
    // package.json
    {
      ...
      "scripts": {
        "dev": "vite"
      },
      ...
    }
    
    1. Finally, run npm run dev in your terminal. If everything is fine, it shall create a webserver and you can run it in your browser.

    localhost server
    html preview

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search