简体   繁体   中英

Import date-fns with npm

I am new to web dev and am following a JS tutorial that is only 1 year old but uses outdated instructions for importing the JS library date-fns with a CDN. I love CDNs, unfortunately only an npm package is available now ( link to documentation ).

I made sure npm was updated then installed date-fns to the desired directory with the following line in terminal:

npm install date-fns --save

There are no more instructions on how to use the package except this example, which I assume goes in the JS file and not the html:

import { formatDistance, subDays } from 'date-fns'

... but using this syntax to try to import the isToday method from the package gives the following warning in my Chrome console:

Uncaught SyntaxError: Cannot use import statement outside a module

This question is asked elsewhere, but there is so much npm-related jargon in those answers I couldn't tell what I was supposed to do. Also, the code was different and older. Does 'module' refer to the npm package?

One would hope a one-year-old tutorial would be new enough to follow. Alas, earwax.

You can get the CDN build of date-fns here: https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js

The import / export won't work in browsers natively, especially if you're trying to work with npm packages. Since you're a beginner, I don't want to confuse you but import / export works in a specific scenario. You can read more about that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Once you're acquainted with web dev, you can try using a bundler such as Parcel which allows you to use npm packages and combine them into a single JS file that can be used in the web: https://parceljs.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM