2

I read code in an app with NextJS. It imports component like import Head from '~/components/layout/head'

The project structure:

-app
---components
---pages
---public

I wonder where defines ~ as root dir in nextJS.

Where can I find the config of this? Tried uncover the webpack config inside next package, but didn't find.

Gasin
  • 51
  • 2
  • 7

3 Answers3

7

With Typescript's paths feature you can specify a module mapping.

// tsconfig.json

{
  "compilerOptions": {
    ...
    "baseUrl": "./",
    "paths": {
      "~/*": ["./src/*"]
    }
    ...
  }
}

This will allow you to import using

import x from '~/components/layout/head';

that will be mapped to src/components/layout/head.

If your are using webpack, you will need to use tsconfig-paths-webpack-plugin.

felixmosh
  • 32,615
  • 9
  • 69
  • 88
  • 1
    Thx for telling! Based on your answer, I find this root path define is done by `babel-plugin-root-import`. – Gasin Oct 24 '19 at 06:38
2

According to the doc.

You can set the module mapping without extra libs.

In your file structure, try this example.

// tsconfig.json 

{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "~*": ["./*]
    }
  }
}

Then go to your files:

import { xxx } from '~/components';

// or

import xxx from '~/components/xxx';
Raymond Yeh
  • 255
  • 2
  • 6
  • 23
0

I find this is because the babel plugin babel-plugin-root-import, since the project uses this plugin in babel config.

More about this plugin can check here.

Gasin
  • 51
  • 2
  • 7