如何从npm模块myLib的index.js引用ES6类并创建实例?
myLib/mod1.js Hey, let's troubleshoot that import error you're seeing. The vast majority of the time, this comes down to a mismatch between how you export your class in mod1.js and how you try to import it in index.js. Let's walk through the most common scenarios:
1. If you're using a default export in mod1.js
If your class is the primary export from mod1.js, use a default export:
// myLib/mod1.js export default class MyAwesomeClass { constructor() { // Your class logic here console.log("Instance created!"); } }
To import this in index.js, you don't need curly braces—just import the class directly (you can even rename it if you want):
// index.js // Import with the original name import MyAwesomeClass from 'myLib/mod1'; // Or rename it for convenience import CustomName from 'myLib/mod1'; // Create your instance const myInstance = new MyAwesomeClass(); // Or using the renamed import const anotherInstance = new CustomName();
2. If you're using a named export in mod1.js
If you're exporting multiple items from mod1.js (or prefer explicit named exports), use this pattern:
// myLib/mod1.js export class MyAwesomeClass { constructor() { console.log("Instance created!"); } } // You might have other exports too, like: export const someUtilityFunction = () => { /* ... */ };
When importing, wrap the class name in curly braces to match the export:
// index.js import { MyAwesomeClass } from 'myLib/mod1'; // Create your instance const myInstance = new MyAwesomeClass(); // If you want to rename the imported class: import { MyAwesomeClass as CustomName } from 'myLib/mod1'; const renamedInstance = new CustomName();
3. Handling CommonJS exports (if myLib uses CommonJS instead of ES6)
Some older npm packages use CommonJS syntax (module.exports) instead of ES6 exports. Adapt your import like this:
- If
mod1.jsexports the class directly:
Import it like a default ES6 export:// myLib/mod1.js (CommonJS) class MyAwesomeClass { /* ... */ } module.exports = MyAwesomeClass;// index.js import MyAwesomeClass from 'myLib/mod1'; const instance = new MyAwesomeClass(); - If
mod1.jsexports an object containing the class:
Use named import syntax:// myLib/mod1.js (CommonJS) class MyAwesomeClass { /* ... */ } module.exports = { MyAwesomeClass };// index.js import { MyAwesomeClass } from 'myLib/mod1'; const instance = new MyAwesomeClass();
Quick Check: Ensure Your Project is Configured for ES Modules
If you're running this in Node.js, add the "type": "module" field to your package.json—this tells Node.js to treat .js files as ES modules instead of CommonJS:
{ "name": "your-project", "type": "module", // ... other project fields }
Double-check that your export and import syntax match, and you should be able to create instances of your class without errors!
内容的提问来源于stack exchange,提问作者The Nomad

