Gasin
Gasin

Reputation: 51

NextJS where defines tilde '~' symbol in import path?

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.

Upvotes: 2

Views: 3790

Answers (3)

felixmosh
felixmosh

Reputation: 35503

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.

Upvotes: 7

Raymond Yeh
Raymond Yeh

Reputation: 285

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';

Upvotes: 2

Gasin
Gasin

Reputation: 51

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.

Upvotes: 0

Related Questions