乐闻世界logo
搜索文章和话题

How to import NPM package in JSFiddle?

1个答案

1

Directly using NPM packages in JSFiddle is not natively supported because JSFiddle is primarily designed as a tool for editing and sharing frontend code snippets, lacking a Node.js environment or direct NPM integration. However, you can indirectly use NPM packages through the following methods:

Using External CDN

The most common approach is to include NPM packages via CDN (Content Delivery Network). Many NPM packages provide a UMD (Universal Module Definition) version that can be directly added to HTML using a <script> tag.

For example, if you want to use the lodash library in JSFiddle, you can:

  1. Visit a website offering CDN links for NPM packages, such as cdnjs or unpkg.
  2. Search for the required library (e.g., lodash).
  3. Copy the provided CDN link.
  4. Add a <script> tag in the JSFiddle HTML section with the link as the src attribute.
html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash/4.17.21/lodash.min.js"></script>

Then, you can directly use lodash functions in your JavaScript section.

Example Code

Suppose you need to use lodash in JSFiddle to remove duplicates from an array. You can implement it as follows:

HTML

html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash/4.17.21/lodash.min.js"></script>

JavaScript

javascript
const arr = [1, 2, 2, 3, 4, 4, 5]; const uniqueArr = _.uniq(arr); console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]

This method is simple and fast, but it relies on the stability and speed of the external CDN.

Summary

While JSFiddle does not natively support importing NPM packages, you can indirectly achieve this by leveraging CDN versions of the libraries. This enables easy testing and sharing of code with popular JavaScript libraries in JSFiddle. For actual project development, you may use Webpack or other module bundlers to manage these dependencies more systematically.

2024年6月29日 12:07 回复

你的答案