Lodash - 环境设置
Lodash - 环境设置
Section titled “Lodash - 环境设置”要开始在您的项目中使用 Lodash,您需要引入该库。根据您的开发环境(浏览器、Node.js、带有打包工具的现代 JavaScript 项目),有几种方法可以做到这一点。
方法 1:在浏览器中使用 Lodash(现代方法)
Section titled “方法 1:在浏览器中使用 Lodash(现代方法)”选项 A:ES 模块 CDN
Section titled “选项 A:ES 模块 CDN”对于支持 ES 模块的现代浏览器,您可以在 <script type="module"> 标签中直接从 CDN 导入 Lodash。这通常适用于小型项目、演示或在线代码编辑器。
<!DOCTYPE html><html><head> <title>Lodash ES 模块示例</title></head><body> <h1>检查控制台!</h1>
<script type="module"> import _ from 'https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/lodash.min.js';
const numbers = [1, 2, 3, 4]; const doubled = _.map(numbers, n => n * 2);
console.log('Original:', numbers); console.log('Doubled:', doubled); console.log('First element:', _.first(numbers)); </script></body></html>注意:使用 lodash-es 提供的是 Lodash 的 ES 模块版本,与现代 import 语法配合良好。
选项 B:传统 CDN Script 标签(旧方法)
Section titled “选项 B:传统 CDN Script 标签(旧方法)”或者,您可以通过标准的 <script> 标签引入 UMD(通用模块定义)构建版本。这使得 Lodash 作为全局变量(通常是 _)可用。此方法常用于较旧的项目或不支持模块的环境。
<!DOCTYPE html><html><head> <title>Lodash 传统 CDN 示例</title> <!-- 引入 Lodash 库 --> <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script></head><body> <div id="output"></div>
<script> // Lodash 作为全局变量 _ 可用 const numbers = [1, 2, 3, 4]; const sum = _.sum(numbers);
document.getElementById('output').innerText = `The sum is: ${sum}`; console.log('Sum calculated using global _:', sum); </script></body></html>方法 2:与 Node.js 或打包工具一起使用 Lodash(推荐用于项目)
Section titled “方法 2:与 Node.js 或打包工具一起使用 Lodash(推荐用于项目)”对于使用 Node.js 进行服务器端开发或使用模块打包工具(如 Webpack、Vite、Rollup、Parcel)的前端项目,标准方法是通过包管理器(npm 或 yarn)安装 Lodash。
步骤 1:安装
Section titled “步骤 1:安装”打开您的项目终端并运行:
# Using npmnpm install lodash
# Or using yarnyarn add lodash这会下载 Lodash 并将其添加到项目的依赖项中(在 package.json 和 node_modules 中)。
为了获得更好的 tree-shaking(移除未使用的代码)效果,特别是在使用现代打包工具时,可以考虑安装特定的 ES 模块版本:
# Using npmnpm install lodash-es
# Or using yarnyarn add lodash-es步骤 2:导入 Lodash
Section titled “步骤 2:导入 Lodash”在您的 JavaScript 文件中,使用 CommonJS (require) 或 ES Module (import) 语法导入 Lodash:
ES 模块语法(推荐)
Section titled “ES 模块语法(推荐)”// 导入整个库 (如果使用 'lodash' 包)import _ from 'lodash';
// 或导入整个库 (如果使用 'lodash-es' 包)import _ from 'lodash-es';
// 您也可以导入特定方法以获得更好的 tree-shaking 效果// (与 'lodash-es' 配合良好,或在打包工具支持时与 'lodash' 配合良好)import map from 'lodash-es/map';import chunk from 'lodash-es/chunk';// or// import { map, chunk } from 'lodash-es';
const data = [1, 2, 3, 4, 5];const chunks = chunk(data, 2);const squares = map(data, n => n * n);
console.log('Chunks:', chunks);console.log('Squares:', squares);CommonJS 语法(Node.js 默认)
Section titled “CommonJS 语法(Node.js 默认)”const _ = require('lodash');
const numbers = [1, 2, 3, 4];const listOfNumbers = _.join(numbers, ', ');
console.log(listOfNumbers); // 输出: 1, 2, 3, 4运行 Node.js 示例
Section titled “运行 Node.js 示例”将上面的 CommonJS 示例保存为 tester.js。然后从终端运行它:
node tester.js输出:
1, 2, 3, 4选择正确的设置方法取决于您的项目需求和工具链(toolchain)。对于大多数现代开发工作流程,使用 npm/yarn 是标准做法。