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

Next.js导入含i18n JSON文件的包时出现模块找不到错误

问题

在Next.js v13.4.3项目中导入了一个包,该包依赖另一个通过JSON文件提供国际化(i18n)翻译的子包。编译时出现以下错误:

- info Collecting page data ..Error: Cannot find module '/Users/user/app/.next/server/chunks/translations.json'
    at webpackEmptyContext (/Users/user/app/.next/server/chunks/7208.js:9:10)
    at Object.9641 (/Users/user/app/.next/server/chunks/9716.js:10551:45)
    at __webpack_require__ (/Users/user/app/.next/server/webpack-runtime.js:25:42)
    at Object.11450 (/Users/user/app/.next/server/chunks/9716.js:5138:31)
    at __webpack_require__ (/Users/user/app/.next/server/webpack-runtime.js:25:42)
    at Object.4847 (/Users/user/app/.next/server/chunks/9716.js:5309:14)
    at __webpack_require__ (/Users/user/app/.next/server/webpack-runtime.js:25:42)
    at Object.59204 (/Users/user/app/.next/server/chunks/9716.js:6898:14)
    at __webpack_require__ (/Users/user/app/.next/server/webpack-runtime.js:25:42)
    at /Users/user/app/.next/server/pages/projects/[id].js:27:79 {
  code: 'MODULE_NOT_FOUND'
}

已确认node_modules中该JSON文件存在,两个包均属于@mycompany NPM作用域,且已添加到transpilePackages数组(["@mycompany"])解决了之前的SyntaxError: Unexpected token 'export'错误。切换到Remix.run也遇到完全相同的错误。

解决方案
  • 配置Next.js的webpack规则处理JSON文件:在next.config.js中扩展webpack配置,确保JSON文件能被正确解析并复制到输出目录。添加如下配置:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      transpilePackages: ["@mycompany"],
      webpack: (config, { isServer }) => {
        // 确保JSON文件被正确处理
        config.module.rules.push({
          test: /\.json$/,
          type: 'asset/resource',
          generator: {
            filename: 'chunks/[name].[hash][ext]'
          }
        });
        return config;
      },
    };
    
    module.exports = nextConfig;
    

    这个配置会把JSON文件作为资源输出到指定目录,避免webpack找不到文件的问题。

  • 检查子包中JSON文件的导入路径与发布配置:确认子包中导入translations.json的是相对路径(比如./translations.json),而非绝对路径。同时在子包的package.json中添加files字段,确保JSON文件被包含在发布包内:

    {
      "files": [
        "dist",
        "translations.json"
      ]
    }
    
  • 清理缓存并重新构建:执行以下命令清除旧缓存和编译文件,避免干扰:

    rm -rf node_modules .next
    npm install
    npm run build
    
  • Remix.run项目的适配配置:在Remix项目的remix.config.js中,添加JSON文件处理规则并确保依赖包被正确打包:

    /** @type {import('@remix-run/dev').AppConfig} */
    export default {
      appDirectory: "app",
      assetsBuildDirectory: "public/build",
      publicPath: "/build/",
      serverBuildPath: "build/index.js",
      devServerPort: 3000,
      serverDependenciesToBundle: ["@mycompany/*"],
      // 添加JSON处理规则
      webpack: (config) => {
        config.module.rules.push({
          test: /\.json$/,
          type: 'asset/resource',
        });
        return config;
      },
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:28:11