You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

无法找到模块"Vector":已安装该包却不知如何导入使用

Fixing "Cannot find module 'Vector'" When Importing the Vector Package

Hey there, let's troubleshoot this import issue together—this is a common gotcha with module naming and environment differences!

1. First, Verify the Package Installation

The npm package is actually named vector (all lowercase)—capitalization matters here! If you installed it with a capitalized name, that's likely part of the problem. Let's fix that first:

# Uninstall the incorrectly named package if you installed it
npm uninstall Vector
# Install the correct lowercase package
npm install vector

Double-check your project's node_modules folder to confirm there's a vector directory inside—this means the package installed successfully.

2. Adjust Your Import Statement to Match the Module System

Looking at the package's source code, it uses CommonJS-style exports (module.exports = Vector). Here's how to import it based on your project's environment:

For CommonJS Environments (Default Node.js Projects)

If your project doesn't have "type": "module" in its package.json, use require:

const Vector = require('vector');

For ES Module Environments

If you've set "type": "module" in your package.json (or using a framework like Vite/React that uses ES modules by default), use import with the lowercase package name:

import Vector from 'vector';

Your original error came partly from using 'Vector' (capitalized) instead of 'vector'—npm package names are case-sensitive!

3. Test with a Quick Example

Once imported correctly, try this simple code to confirm it's working:

// Create two vectors
const v1 = new Vector(2, 3);
const v2 = new Vector(4, 5);

// Use a built-in method like add()
const sum = v1.add(v2);
console.log(sum); // Should output Vector { x: 6, y: 8 }

4. For Browser Environments (No Node.js)

If you're using this directly in a browser without a build tool, skip npm installation and include the source script directly:

<script src="./path/to/vector.js"></script>
<script>
  const myVector = new Vector(10, 10);
  console.log(myVector.magnitude()); // Calculates the vector's length
</script>

Just make sure the src path points to where you saved the vector.js file from the repo.

内容的提问来源于stack exchange,提问作者Ian Jones

火山引擎 最新活动