【问题标题】:Dynamic import in NodeJS (in Gatsby): A dynamic import callback was not specifiedNodeJS 中的动态导入(在 Gatsby 中):未指定动态导入回调
【发布时间】:2020-10-07 10:20:48
【问题描述】:

我正在尝试在 NodeJS 中使用动态导入,带有一个 eS6 文件,但无法正常工作

我在其gatsby-node.js 文件中的gatsby 项目中使用它

exports.createPages = async props => {
  
  //...

  const name = './test'
  ;(async () => {
    const data = await import(name)
    console.log(data)
  })()

test.js 在哪里

export const hey = 'hi'

但我总是得到这个A dynamic import callback was not specified.

为什么它不起作用? NodeJS 版本为12.18.4

【问题讨论】:

    标签: node.js import gatsby dynamic-import


    【解决方案1】:

    由于它目前不是发布版本,您需要安装 ES6 的每个所需模块(在您的情况下为 babel-plugin-syntax-dynamic-import)并将其添加到您的 babel 配置中。

    运行:

    npm install --save-dev @babel/plugin-syntax-dynamic-import
    

    然后,在你的 Babel 文件(项目根目录中的babel.config.js.babelrc)中将其添加到plugins 数组中:

      "plugins": ["@babel/plugin-syntax-dynamic-import"]
    

    理想情况下,您的 Babel 文件应如下所示:

    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 };
    };
    

    【讨论】:

    猜你喜欢
    • 2023-02-01
    • 2020-01-20
    • 2022-12-22
    • 2021-02-03
    • 2020-10-27
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多