简体   繁体   English

使用 npm 导入 date-fns

[英]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.我是 Web 开发新手,正在学习一个只有 1 年历史的 JS 教程,但使用过时的说明来导入带有 CDN 的 JS 库 date-fns。 I love CDNs, unfortunately only an npm package is available now ( link to documentation ).我喜欢 CDN,不幸的是,现在只有一个 npm 包可用(链接到文档)。

I made sure npm was updated then installed date-fns to the desired directory with the following line in terminal:我确保 npm 已更新,然后在终端中使用以下行将 date-fns 安装到所需目录:

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:除了这个例子之外,没有更多关于如何使用包的说明,我假设它在 JS 文件中而不是在 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: ...但使用此语法尝试从包中导入 isToday 方法会在我的 Chrome 控制台中给出以下警告:

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.这个问题在别处被问到,但这些答案中有太多与 npm 相关的术语,我不知道我应该做什么。 Also, the code was different and older.此外,代码不同且更旧。 Does 'module' refer to the npm package? “模块”是指 npm 包吗?

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您可以在此处获取date-fns的 CDN 构建: https : date-fns

The import / export won't work in browsers natively, especially if you're trying to work with npm packages. import / export本机无法在浏览器中工作,尤其是当您尝试使用 npm 包时。 Since you're a beginner, I don't want to confuse you but import / export works in a specific scenario.由于您是初学者,我不想让您感到困惑,但import / export在特定场景中有效。 You can read more about that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules您可以在此处阅读更多相关信息: 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/一旦你熟悉了 web dev,你可以尝试使用一个打包器,比如 Parcel,它允许你使用 npm 包并将它们组合成一个可以在 web 中使用的单个 JS 文件: https : //parceljs.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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