Next.js-导入TypeScript模块时找不到模块

时间:2020-08-14 07:11:08

标签: typescript next.js es6-modules

这是我的代码:

// lib/test2.ts

export function test2() {
  console.log("test2");
}
// pages/index.tsx

import { GetServerSideProps } from "next";
// works
import { test } from "../lib/test.js";
// error
import { test2 } from "../lib/test2.js";

export const getServerSideProps: GetServerSideProps = async ({
  req,
}): Promise<{ props: {} }> => {
  test();
  test2();
  return { props: {} };
};

export default function Home(props: {}) {
  return <div>Hi</div>;
}

运行此代码时,我得到

Module not found: Can't resolve '../lib/test2.js' in '/Users/USER/Documents/software/nextjs-test/pages'

我不确定为什么。 lib/test2.ts是否应该编译为lib/test2.js,并且导入应该正常?我想我对TypeScript混在一起时如何真正解决导入问题不太熟悉。

链接到此处的所有代码:Playground

2 个答案:

答案 0 :(得分:1)

这是正在发生的事情的要旨。

webpack在Compilation.js中抛出了ModuleNotFoundError

原因是因为webpack是将TypeScript实际编译为JavaScript的东西。 post提供了不错的解释。

如果添加

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    console.log(config);
    config.module.rules.map((rule) => console.log(JSON.stringify(rule)));
    return config;
  },
};

next.config.js,您可以看到Next.js使用的webpack配置。显然,他们在捆绑之前使用next-babel-loader将TypeScript编译为JavaScript。

总之,正在发生的是:

  1. webpack尝试在../lib/test2.js中找到Compilation.js。在所有内容都未编译为JavaScript之前。
  2. ../lib/test2.js不存在,因为../lib/test2.ts尚未编译成JavaScript。
  3. 引发错误。

答案 1 :(得分:0)

只需安装 babel 软件包即可。详情请见https://www.npmjs.com/package/babel-loader

npm install -D babel-loader @babel/core @babel/preset-env webpack

相关问题