Reputation: 4341
I'm trying to use the dynamic imports in NodeJS, with a eS6 file, but can't get it work
I'm using it in a gatsby
project within its gatsby-node.js
file
exports.createPages = async props => {
//...
const name = './test'
;(async () => {
const data = await import(name)
console.log(data)
})()
Where test.js
is just
export const hey = 'hi'
But I always get this A dynamic import callback was not specified.
Why is it not working? NodeJS version is 12.18.4
Upvotes: 5
Views: 22631
Reputation: 29335
The syntax should be valid without importing any additional plugins with Babel.
If you need them or need to tweak/customize its configuration, please continue reading.
Since it's not currently a publish version, you need to install each desired module (babel-plugin-syntax-dynamic-import
in your case) of ES6 and add it yo your babel configuration.
Run:
npm install --save-dev @babel/plugin-syntax-dynamic-import
Then, in your Babel file (babel.config.js
or .babelrc
in the root of your project) add it to plugins
array:
"plugins": ["@babel/plugin-syntax-dynamic-import"]
Ideally, your Babel file should look like:
module.exports = function(api) {
api.cache(true);
const presets = [
[`@babel/preset-env`, { 'useBuiltIns': `usage`, 'corejs': `2` }],
[`@babel/preset-react`, { 'development': true, minify: true }],
];
const plugins = [
`@babel/plugin-syntax-dynamic-import`,
];
return { presets, plugins };
};
Upvotes: 0