Reputation: 6013
I'm working with a React/NodeJS project where I want to be able to conditionally import a Node module if and only if a parameter is not passed to my component via a prop
const WysiwygField = ({ onChange, autoFocus, field, errors, value: serverValue }) => {
if (!field.config.apiKey) import tinymce from 'tinymce/tinymce';
....
}
I suspect because of the way Node modules work that this isn't possible. I've done some googling but am getting confused between the concept of conditional importing -- which https://javascript.info/modules-dynamic-imports seems to say one can't do in NodeJS and dynamic importing, for which there seems to be Babel support: https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import.
Is this a dead-end, or is there any way to do what I want to do? (The reason for this is because of the way that tinymce-react
works: if the TinyMCE package hasn't been imported, then it goes to the CDN, where the passed apiKey
is of use. The reason why I don't just code it that way to begin with, that is, just make sure it never loads the local library, is because I'm working within a larger framework where I don't have the liberty to preclude that option).
Upvotes: 2
Views: 1679
Reputation: 307
You can use Dynamic Imports
to achieve this.
Like:
const A = condition && import('./a.js')
Although to use dynamic imports you will have to use babel
.
Upvotes: 2
Reputation: 10021
I believe you can do conditional imports with the require syntax - something like:
let someImport;
if (condition) someImport = require('module');
Upvotes: 3