Dynamic import a file with ember-auto-import that is not located in node_modules folder

Hi there!

I’m trying to dynamic import a file with ember-auto-import that is not located in node_modules folder and I having problems.

I’m using pdfmake to create PDF files in the client and when I use ember-auto-import to load dynamically the library and the fonts it works perfectly fine:

@dropTask
*createPDF() {
    let pdfMake = yield import('pdfmake/build/pdfmake.min').then(module => module.default);
    let pdfFonts = yield import('pdfmake/build/vfs_fonts').then(module => module.default);
    pdfMake.vfs = pdfFonts.pdfMake.vfs;
    ...
}

With this library you can use your own custom fonts so I have a file with the fonts definition stored in my project but when I try to import it the same way I have a runtime error: Error: Could not find module '_eai_dyn_myapp/pdf/my-custom-fonts' imported from '(require)'

The file is stored in a folder named pdf inside my app folder:

myapp
|-- app
    |-- pdf
        |-- my-custom-fonts.js

This is how I import it:

@dropTask
*createPDF() {
    let pdfMake = yield import('pdfmake/build/pdfmake.min').then(module => module.default);
    // first option
    let pdfFonts = yield import('myapp/pdf/my-custom-fonts').then(module => module.default);
    // second option (a relative path)
    let pdfFonts = yield import('../../pdf/my-custom-fonts').then(module => module.default);
    pdfMake.vfs = pdfFonts.pdfMake.vfs;
    ...
}

With both options I get the mentioned runtime error. How can I import the file?

Thank you.

Unfortunately ember-auto-import does not support importing things out of your app’s own package, or out of any package that declares itself to be an ember addon. The reason for this is that traditional Ember apps and addons have their own ways of getting modules into the build and ember-auto-import can’t really control them.

(Making this kind of import Just Work everywhere is part of Embroider is doing.)

Your best workaround right now is to make a separate package to hold the files you want to dynamically import. It doesn’t need to be a real published package, it can be a subdirectory of your repo that has its own package.json file:

├── app
├── lib
│   └── my-custom-fonts
│       ├── index.js
│       └── package.json
└── package.json

And the main package.json can depend on it like:

"dependencies": {
  "my-custom-fonts": "file:./lib/my-custom-fonts"
}

I think that should be enough to let you auto-import out of the my-custom-fonts package.

5 Likes

It’s perfect. And I realize I have too much to learn! :rofl:

I know Embroider and I have done a little test in a toy app but in this case I’m working in a production app and I can’t test it right know. I hope to use it in future apps from the beginning.

Thank you very much!