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

如何将TypeScript文件中的函数导入next.config.mjs?

解决Next.js中从next.config.mjs导入TypeScript辅助函数的问题

直接在next.config.mjs中导入.mts或.ts文件会报错,因为Node.js无法直接解析TypeScript代码,而next.config.mjs是由Node.js直接执行的ES模块。以下是几种可行的解决方案:

方案一:编译TypeScript文件后导入编译产物

  1. 确保你的tsconfig.json配置了正确的输出目录与模块规则:
    {
      "compilerOptions": {
        "outDir": "./dist",
        "module": "ESNext",
        "moduleResolution": "NodeNext",
        "target": "ES2020"
      },
      "include": ["utils.mts"]
    }
    
  2. 运行TypeScript编译命令,将utils.mts转译为JS文件:
    tsc
    
    也可以在package.json中添加编译脚本,方便重复执行:
    "scripts": {
      "build:utils": "tsc --project tsconfig.json"
    }
    
  3. 在next.config.mjs中导入编译后的JS文件:
    import { yourHelperFunction } from './dist/utils.mjs';
    
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      webpack: (config) => {
        // 使用导入的辅助函数配置loader
        config.module.rules.push(yourHelperFunction());
        return config;
      }
    };
    
    export default nextConfig;
    
    注意:每次修改utils.mts后都需要重新编译,或使用tsc --watch监听文件变化自动编译。

方案二:用ts-node直接运行TypeScript版的配置文件

  1. 安装必要依赖:
    npm install --save-dev ts-node typescript
    
  2. 将next.config.mjs重命名为next.config.ts,直接在其中导入TypeScript辅助函数:
    import { yourHelperFunction } from './utils.mts';
    import type { NextConfig } from 'next';
    
    const nextConfig: NextConfig = {
      webpack: (config) => {
        config.module.rules.push(yourHelperFunction());
        return config;
      }
    };
    
    export default nextConfig;
    
  3. 修改package.json中的启动脚本,用ts-node执行Next.js命令:
    "scripts": {
      "dev": "ts-node --esm node_modules/next/dist/bin/next dev",
      "build": "ts-node --esm node_modules/next/dist/bin/next build",
      "start": "ts-node --esm node_modules/next/dist/bin/next start"
    }
    
    这种方式适合开发阶段,无需手动编译TypeScript文件。

方案三:将辅助函数转为纯JavaScript文件

如果辅助函数逻辑不复杂,可直接将utils.mts中的代码复制到utils.mjs文件中,保持逻辑一致,然后在next.config.mjs中直接导入这个JS版本的文件:

import { yourHelperFunction } from './utils.mjs';

这种方式最直接,避免了编译和依赖管理的额外操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:12:40