如何将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文件后导入编译产物
- 确保你的
tsconfig.json配置了正确的输出目录与模块规则:{ "compilerOptions": { "outDir": "./dist", "module": "ESNext", "moduleResolution": "NodeNext", "target": "ES2020" }, "include": ["utils.mts"] } - 运行TypeScript编译命令,将
utils.mts转译为JS文件:
也可以在tscpackage.json中添加编译脚本,方便重复执行:"scripts": { "build:utils": "tsc --project tsconfig.json" } - 在
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版的配置文件
- 安装必要依赖:
npm install --save-dev ts-node typescript - 将
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; - 修改
package.json中的启动脚本,用ts-node执行Next.js命令:
这种方式适合开发阶段,无需手动编译TypeScript文件。"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" }
方案三:将辅助函数转为纯JavaScript文件
如果辅助函数逻辑不复杂,可直接将utils.mts中的代码复制到utils.mjs文件中,保持逻辑一致,然后在next.config.mjs中直接导入这个JS版本的文件:
import { yourHelperFunction } from './utils.mjs';
这种方式最直接,避免了编译和依赖管理的额外操作。
内容的提问来源于stack exchange,提问作者Kranthi S
相关产品推荐
相关产品推荐

