如何修改资产、图片等的基础路径

7
我需要我的应用程序在主域名的子文件夹中正常工作。精确地说这里。 起初,我遇到了许多脚本、CSS和图像无法加载的错误。
我在next.config.js中添加了以下内容:
basePath: "/out",

现在脚本和css在导出时运作良好,它们的路径中有“/out/”。
但是文件路径中还没有“/out/”,因此它们会出现404错误。
我尝试按照this教程操作,但似乎我仍然做错了些什么。
我的next.config.js现在是:
const path = require("path");

module.exports = {
  trailingSlash: true,
  sassOptions: {
    includePaths: [path.join(__dirname, "styles")],
  },

  basePath: "/out",
  assetPrefix: process.env.BASE_PATH || '',
  publicRuntimeConfig: {
    basePath: process.env.BASE_PATH || '',
  },
};

相关的package.json代码如下:

"scripts": { "dev": "node server.js -p $PORT", "build": "next build", "prod": "BASE_PATH=/out next build && next export", "start": "NODE_ENV=production node server.js -p $PORT", "start2": "next start" },

server.js 代码如下:

const express = require('express');
const next = require('next');
const path = require('path');
const bodyParser = require('body-parser');
const keys = require("./server/config/keys");
const stripe = require('stripe')(keys.stripeSecretKey);
const routes = require('./routes');

const dev = process.env.NODE_ENV !== 'production';

const app = next({ dir: '.', dev });
const handle = routes.getRequestHandler(app);

app.prepare().then(() => {
    const server = express();
        // Static files
        // https://github.com/zeit/next.js/tree/4.2.3#user-content-static-file-serving-eg-images
    server.use('/images', express.static(path.join(__dirname, 'images'), {
        maxAge: dev ? '0' : '365d'
    }));

    server.use(bodyParser.json());

    server.get('*', (req, res) => {
        return handle(req, res)
    });

    server.post('/api/stripe/checkout', async (req, res) => {
        await stripe.charges.create({
            amount: req.body.amount,
            currency: 'usd',
            description: 'Mojosa - React Next Landing Page Templates',
            source: req.body.token.id
        });
        res.send({})
    });

    const PORT = process.env.PORT || 3000;

    server.listen(PORT, (err) => {
        if (err) throw err
        console.log(`> Read on http://localhost:${PORT}`)
    });
})

这里有一个组件中图像的示例:

<div className="col-lg-6 col-md-12">
    <div className="book-image">
    <img src='/images/book-img.png' alt="image" />
</div>

使用这个配置:

  • EXPORT - 当上传到实际网站时,next build && next export在/out/文件夹上正常工作,但图像会出现404错误。
  • DEV或BUILD它们会出现404错误,并且比发布在实际域上的EXPORT网站工作得更差。如果我删除basePath: "/out",开发模式将非常出色。

问题: 如何使所有图像/资产都添加到/out/路径中? 当导出时,我可以重新添加basePath: "/out"


我发现这个链接很有用 https://levelup.gitconnected.com/deploy-your-nextjs-application-on-a-different-base-path-i-e-not-root-1c4d210cce8a - karianpour
1个回答

14

我也遇到了这个问题。您需要手动在公共文件夹中添加前缀(图像、字体等),与您的basePath相对应。

文档 “位于public文件夹中的文件;如果要通过CDN提供这些资源,您必须自己引入前缀”

<div className="col-lg-6 col-md-12">
    <div className="book-image">
    <img src={`${process.env.BASE_PATH}/images/book-img.png`} alt="image" />
</div>

4
你有解决在 CSS 中加载字体和图片的方案吗?由于环境变量不可访问,建议的解决方案不可行。 - Flavio
1
你需要在 next.config.js 中设置如下内容: publicRuntimeConfig: { basePath: process.env.BASE_PATH || '' } 这样就可以通过以下方式访问: import getConfig from 'next/config'; const { publicRuntimeConfig } = getConfig() - Matt Jensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接