【问题标题】:Next.js export failing due to import?Next.js 导出因导入而失败?
【发布时间】:2020-02-21 13:25:00
【问题描述】:

导出我的 nextjs 应用时出现以下错误:

SyntaxError: Unexpected token {
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)

这是我的next.config.js

import {getBlogPosts} from "./src/api";
import {mapPosts} from "./src/mappers/BlogMapper";
module.exports = {
    async exportPathMap() {
        const response = await getBlogPosts();
        const posts = mapPosts(response);
        const pages = posts.reduce(
            (pages, post) =>
                Object.assign({}, pages, {
                    [`/blog/${post.uid}`]: {page: '/blog/[uid]'},
                }),
            {}
        );
        // combine the map of post pages with the home
        return Object.assign({}, pages, {
            '/': {page: '/'},
        })
    },
};

src/api 文件:

import Prismic from "prismic-javascript";
import {Client} from "./prismic-configuration";
export const getBlogPosts = (req) => {
    return Client(req).query(
        Prismic.Predicates.at("document.type", "post"),
        {orderings: "[my.post.date desc]"}
    );
};
export const getBlogPost = (req, uid) => {
    return Client(req).getByUID("post", uid, null);
};

我在文档中发现了这个问题,但我不确定由谁来解决它:

避免使用目标中不可用的新 JavaScript 功能 Node.js 版本。 next.config.js 不会被 Webpack、Babel 解析 或 TypeScript。

【问题讨论】:

    标签: javascript webpack next.js


    【解决方案1】:

    next.config.js: 的代码是使用 ES6 语法编写的。

    你应该把它转换成 CommonJS

    试试这样:

    const getBlogPosts = require('./src/api').getBlogPosts
    const mapPosts = require('./src/mappers/BlogMapper').mapPosts
    
    module.exports = {
        exportPathMap: async function () {
            const response = await getBlogPosts();
            const posts = mapPosts(response);
            const pages = posts.reduce(
                (pages, post) =>
                    Object.assign({}, pages, {
                        [`/blog/${post.uid}`]: {page: '/blog/[uid]'},
                    }),
                {}
            );
            // combine the map of post pages with the home
            return Object.assign({}, pages, {
                '/': {page: '/'},
            })
        },
    };
    

    【讨论】:

    • 我认为这确实是问题所在,但现在仍然出现“{ Error: Cannot find module './src/api'' 错误。我是否在 src/api 中以错误的方式导出?
    • 你可以在这里找到它:github.com/Jdruwe/jeroendruwe,只需运行 yarn install 和 yarn export。如果我尝试使用 module.exports 导出函数,我将收到“所有文件必须是模块,当提供 '--isolatedmodules' 标志时”警告,这是由 next.js 预先配置的,但它似乎是必需的(@ 987654322@)
    • 是的,您应该转换next.config.js中所需的所有代码
    • 感谢所有帮助,现在将其转换,很遗憾不支持 es6 模块,可能是出于某种原因,但是是的...
    猜你喜欢
    • 1970-01-01
    • 2016-03-17
    • 2015-06-22
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多