zazoomauro / node-dependency-injection

The NodeDependencyInjection component allows you to standarize and centralize the way objects are constructed in your application.
https://github.com/zazoomauro/node-dependency-injection/wiki
MIT License
276 stars 34 forks source link

Require of ES Module not supported #183

Closed AntonKrychevskyy closed 1 year ago

AntonKrychevskyy commented 2 years ago

Have small educational example for initial exploration of DI.

import * as path from 'path';
import { fileURLToPath } from 'url';
import { ContainerBuilder, YamlFileLoader } from 'node-dependency-injection';

console.log('Hello, this is Homework #06');

const container = new ContainerBuilder();
const loader = new YamlFileLoader(container);
const configPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'config.yml');
await loader.load(configPath);

container.get('car').start();
services:
    car:
        class: ./car
        arguments: ['Mercedes', 'SLS AMG', '@dieselEngine', '2022']
    dieselEngine:
        class: ./diesel-engine
        arguments: []
        calls:
            - { method: 'setHp', arguments: ['600'] }

Don't think there is any sense to put here other files content.

It fails when I run node src/app.js due to services are imported with require() statement.

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/anton/Projects/patterns-js/patterns/lesson_06/homework_06/src/car.js from /Users/anton/Projects/patterns-js/patterns/lesson_06/homework_06/node_modules/node-dependency-injection/dist/lib/Loader/FileLoader.js not supported.
Instead change the require of car.js in /Users/anton/Projects/patterns-js/patterns/lesson_06/homework_06/node_modules/node-dependency-injection/dist/lib/Loader/FileLoader.js to a dynamic import() which is available in all CommonJS modules.

If I change all files from ES modules to CommonJS, and remove "type": "module" in package.json all works fine. But it is disappointing cause your docs full of examples written as ES modules.

zazoomauro commented 1 year ago

Hello @AntonKrychevskyy ... but I still not getting it

I have a project with require instead of import and it work properly. remember that your class needs to be on export default