简体   繁体   中英

Next.js - module not found when importing TypeScript module

Here's my code:

// 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>;
}

When I run this code, I get

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

I'm not sure why. Shouldn't lib/test2.ts compile to lib/test2.js , and the import should be fine? I suppose I'm not very familiar with how the imports actually get resolved when TypeScript is in the mix.

Link to all the code here: https://github.com/arcticmatt/nextjs-test

Here's the gist of what's happening.

webpack is throwing a ModuleNotFoundError in Compilation.js .

The reason is because webpack is the thing that actually compiles TypeScript to JavaScript. This post provides a decent explanation.

If you add

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

to next.config.js , you can see the webpack config that Next.js uses. Apparently they use the next-babel-loader to compile TypeScript to JavaScript before bundling it.

In, summary, what's happening is:

  1. webpack tries to find ../lib/test2.js in Compilation.js . This is before anything has been compiled to JavaScript.
  2. ../lib/test2.js doesn't exist, since ../lib/test2.ts hasn't been compiled to JavaScript yet.
  3. An error is thrown.

The solution is to omit the file extension and write import { test2 } from "../lib/test2"; . You can clone the repo I linked in the OP and run yarn dev to verify this works.

Just install the babel packages and you are good to go. Details here https://www.npmjs.com/package/babel-loader .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM