Webpack resolve.alias does not work with typescript?

前端 未结 7 1178
日久生厌
日久生厌 2020-12-12 21:02

I try to shorten my imports in typescript

from import {Hello} from \"./components/Hello\";

to import {Hello} from \"Hello\";

<
7条回答
  •  清歌不尽
    2020-12-12 21:21

    As others have mentioned, you need to provide an alias in your webpack.config.js:

        resolve: { 
    
            extensions: [".ts", ".js"],
            alias: {
                forms: path.resolve(__dirname, "src/forms/")
            } 
        },
    

    This needs to be in synch with your tsconfig.json file (baseUrl and paths are required).

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

    Note: The wildcard pattern is necessary to match with your resolve alias configuration.

    Then you can import any library using your alias:

    import { FormsModule } from "forms/my-forms/my-forms.module";
    

提交回复
热议问题