导入nearestColor模块遇Uncaught TypeError错误,求解决方案
解决nearestColor模块导入错误的方案
错误原因分析
- 第一个错误
Uncaught TypeError: Cannot set properties of undefined (setting 'nearestColor'):
当你用type="module"的脚本引入时,ES模块环境下顶层this为undefined,自执行函数的参数context因此变成undefined,无法给它设置nearestColor属性。 - 第二个错误
Uncaught ReferenceError: nearestColor is not defined:nearestColor是自执行函数内部定义的变量,模块顶层的export default nearestColor无法访问到这个内部变量,导致报错。
方案1:使用传统全局脚本引入(最简单)
去掉脚本的type="module"属性,让代码运行在全局作用域,此时自执行函数的this指向window,context即为window,代码会自动把nearestColor挂载到全局:
<script src="https://cdn.jsdelivr.net/gh/dtao/nearest-color@master/nearestColor.js"></script> <script> // 直接使用全局的nearestColor const colorMatcher = nearestColor.from(['#ff0000', '#00ff00', '#0000ff']); console.log(colorMatcher('#ff3333')); </script>
方案2:适配ES模块引入
如果必须用ES模块(type="module"),需要修改原代码的导出逻辑,让模块能正确暴露nearestColor:
- 复制原CDN的代码到本地文件(比如
nearestColor.js) - 修改文件末尾的代码:
const nearestColor = (function(context) { // 原代码内部所有逻辑保持不变 // 保留UMD导出逻辑,最后返回nearestColor if (typeof module === 'object' && module && module.exports) { module.exports = nearestColor; } else if (context) { context.nearestColor = nearestColor; } return nearestColor; }(typeof window !== 'undefined' ? window : undefined)); export default nearestColor; - 在你的模块脚本中导入使用:
import nearestColor from './nearestColor.js'; const colorMatcher = nearestColor.from(['red', 'green', 'blue']); console.log(colorMatcher('#00ff00'));
方案3:使用npm包本地安装(推荐生产环境)
如果是项目开发,更稳定的方式是安装npm包:
npm install nearest-color
然后根据项目模块规范导入:
// CommonJS const nearestColor = require('nearest-color'); // ES模块 import nearestColor from 'nearest-color';
内容的提问来源于stack exchange,提问作者prislei
相关产品推荐
相关产品推荐

