Nextjs 中的 @Babylonjs (ES6) 因意外标记“导出”而失败

Emi*_*ile 3 babylonjs next.js

我正在使用 Nextjs 构建我的网站,导入 Bablyonjs 时出现以下错误。

syntaxError: Unexpected token 'export'
module.exports = require("@babylonjs/core")
Run Code Online (Sandbox Code Playgroud)

我正在使用带有 tsconfig.json 的标准 nextjs 设置我正在参考这个 Babylon 文档并逐字使用示例。

在此处输入图片说明

Emi*_*ile 10

经过一段不那么微不足道的搜索时间,我终于了解到以下内容。

  1. @babylon (es6) 没有编译成 javascript,而是很好地定义 (es6) 打字稿友好的源代码库。(当想要摇树时有帮助)

  2. 开箱即用的 Nextjs 未配置为编译 node_modules 中的任何内容。它需要准备好使用的预编译 javascript。

第 2 点是我收到错误的原因,nextjs 期待已编译的 js 并且它正在获取未编译的源代码。

为了解决这个问题,你需要添加一个next.config.js与配置它next-transpile-modulesnext-compose-plugins

yarn add next-transpile-modules
yarn add next-compose-plugins
Run Code Online (Sandbox Code Playgroud)

下一个.config.js

//const withTM = require('next-transpile-modules')(['@babylonjs']);
const withTM = require('next-transpile-modules')(['@babylonjs/core']); // As per comment.
const withPlugins = require('next-compose-plugins');

const nextConfig = {
    target: 'serverless',
    webpack: function (config) {
        /// below is not required for the problem described. Just for reference.(es6)
        config.module.rules.push({test: /\.yml$/, use: 'raw-loader'})
        return config
    }
}

module.exports = withPlugins([withTM], nextConfig);
Run Code Online (Sandbox Code Playgroud)

在此之后它编译没有错误。

参考资料 我在解决这个问题时遇到了方便的链接。

帮助一些人了解问题的链接。