Angular 5 CLI中如何导入/引用自定义Node模块?
foo-bar Node Module Hey there! Let's walk through how to work with this foo-bar module based on what you've shared. Let's start by breaking down what the module's root index.js is actually doing, then cover practical usage steps.
First, Understand the Module's Setup
Looking at the root index.js:
require('./dist/js/foo'); module.exports = 'foo';
All this does is two simple things:
- It executes the code in
dist/js/foo.js(so any logic or exposed functionality in that file will run/be made available). - It exports the plain string
'foo'—which is almost certainly not the actual functionality you're trying to use.
So the real "meat" of the module lives in dist/js/foo.js.
Step 1: Import the Module to Load Its Logic
In your app.component.ts, start by importing the module to trigger the execution of dist/js/foo.js:
// This runs all the code in dist/js/foo.js import 'foo-bar';
If you're using CommonJS syntax instead:
require('foo-bar');
Just a heads-up: if you try to import the exported string, it'll only give you the value 'foo'—which is rarely useful:
import foo from 'foo-bar'; console.log(foo); // Logs: 'foo'
So focus on the functionality loaded from dist/js/foo.js instead.
Step 2: Access the Actual Module Functionality
You'll need to peek inside node_modules/foo-bar/dist/js/foo.js to see how it exposes its features. Here are the two most common scenarios:
- Case 1: It exports variables/classes/functions
If the file usesmodule.exportsor ES6exportsyntax, you can import directly from this file instead of the module root:// Example: If foo.js exports a Foo class import { Foo } from 'foo-bar/dist/js/foo'; const myFoo = new Foo(); myFoo.doSomething(); - Case 2: It attaches to the global scope
Some modules add variables towindow(in browsers) orglobal(in Node). If you see code likewindow.Foo = ...in the file, you can access it after importing the module:import 'foo-bar'; // TypeScript needs a type assertion here to avoid errors const myFoo = new (window as any).Foo();
Step 3: Use CSS and Image Assets
Don't forget about the module's static assets:
- CSS: Import the CSS file directly into your component or global stylesheet:
// In app.component.ts import 'foo-bar/dist/css/[your-css-filename].css'; - Images: Reference images from the
foo-imagesdirectory using a relative path. For example, in Angular, you might write:
For cleaner pathing, you can also copy the images to your project's<img src="../node_modules/foo-bar/dist/foo-images/[your-image-filename].png" alt="Foo module image">assetsdirectory.
Quick Troubleshooting Tips
- Check the
package.jsonoffoo-bar—look for amainfield (though it points to the rootindex.jshere) or aREADME.mdfile (if it exists) for official usage instructions. - If
dist/js/foo.jsis minified, use a tool like Prettier to format it so you can read the code more easily.
内容的提问来源于stack exchange,提问作者o.o

