使用JavaScript导入Pokemon TCG SDK时模块解析失败的解决方法
解决Pokemon TCG SDK在XAMPP环境中模块导入失败的问题
我正尝试使用Pokemon TCG SDK开发宝可梦卡牌库,已获取API密钥并在本地XAMPP环境通过npm安装了该JavaScript实现,但在导入模块时遇到了问题。
我的HTML代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>TCG</title> </head> <body> <script type="module" src="script.js"></script> </body> </html>
script.js代码:
import pokemon from 'pokemontcgsdk' pokemon.configure({apiKey: 'myAPIkey'}) pokemon.card.find('base1-4') .then(card => { console.log(card.name) // "Charizard" })
运行后出现错误:
Failed to resolve module specifier "pokemontcgsdk". Relative references must start with either "/", "./", or "../".
我尝试在导入时使用“/”、“./”或“../”,比如import pokemon from '../pokemontcgsdk',但又出现404错误。
解决方案
1. 直接使用相对路径指向SDK入口文件
浏览器无法直接识别npm模块名的裸导入,你需要找到node_modules目录下Pokemon TCG SDK的实际入口文件(通常在dist文件夹内的index.js),用相对路径导入。
假设script.js和node_modules在同一级目录,修改导入语句为:
import pokemon from './node_modules/pokemontcgsdk/dist/index.js'
(若文件夹结构不同,自行调整路径至实际入口文件位置)
2. 使用导入映射(Import Maps)
在HTML中添加importmap,将模块名映射到实际文件路径,这样可以保留原导入语句:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>TCG</title> <script type="importmap"> { "imports": { "pokemontcgsdk": "./node_modules/pokemontcgsdk/dist/index.js" } } </script> </head> <body> <script type="module" src="script.js"></script> </body> </html>
配置后script.js里的import pokemon from 'pokemontcgsdk'即可正常运行。
3. 使用前端打包工具(推荐)
直接在浏览器中使用npm模块易出现路径解析问题,更稳妥的方式是用Vite、Webpack这类打包工具:
- 初始化项目并安装依赖
- 配置打包工具后,生成浏览器可识别的打包文件
- 在XAMPP中部署打包后的产物,模块导入问题会被工具自动处理
内容的提问来源于stack exchange,提问作者mark-in-motion
相关产品推荐
相关产品推荐

