You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify Remix中_index.tsx无法访问/public/文件的技术问询

在Shopify Remix中访问公共目录资源的正确方式

方案1:服务器端直接读取文件(适合.txt这类需解析内容的场景)

你的代码运行在服务器端时,fetch("/countries.txt")因缺少完整域名和协议导致URL解析失败,直接读取文件系统是更高效的方式:

  1. 引入Node.js文件模块:
import fs from "fs/promises";
import path from "path";
  1. 在loader函数(推荐)或组件中读取文件:
export async function loader() {
  // 拼接public目录的绝对路径
  const countriesFilePath = path.join(process.cwd(), "public", "countries.txt");
  // 读取文件内容
  const countriesContent = await fs.readFile(countriesFilePath, "utf-8");
  // 处理内容,比如转成数组
  const countriesList = countriesContent.split("\n").filter(Boolean);
  
  return json({ countriesList });
}

// 在组件中使用数据
export default function Index() {
  const { countriesList } = useLoaderData<typeof loader>();
  
  return (
    <div>
      <h1>国家列表</h1>
      <ul>
        {countriesList.map((country) => (
          <li key={country}>{country}</li>
        ))}
      </ul>
    </div>
  );
}

方案2:构建完整URL进行fetch(适合需通过HTTP请求访问的场景)

如果必须使用fetch,需拼接完整站点URL,可通过loader的request对象获取当前域名:

export async function loader({ request }: LoaderFunctionArgs) {
  const url = new URL(request.url);
  // 拼接公共资源的完整URL
  const countriesUrl = new URL("/countries.txt", url.origin);
  const response = await fetch(countriesUrl);
  
  if (!response.ok) {
    throw new Response("文件不存在", { status: 404 });
  }
  
  const countriesContent = await response.text();
  const countriesList = countriesContent.split("\n").filter(Boolean);
  
  return json({ countriesList });
}

图片等静态资源的访问方式

对于.png这类仅需展示的资源,直接在组件中使用相对路径即可,Remix会自动处理:

export default function Index() {
  return (
    <img src="/logo.png" alt="品牌logo" />
  );
}

注意事项

  • 确保文件放在public根目录下,路径需与代码中引用的一致。
  • 服务器端读取文件时,Shopify Remix部署环境默认会确保public目录的读取权限。

内容的提问来源于stack exchange,提问作者JTR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:52:12