Import module from root path in TypeScript

后端 未结 5 1841
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 23:02

Let\'s suppose I\'ve a project, and its main source directory is:

C:\\product\\src

Based on this directory, every import path would be rela

5条回答
  •  清酒与你
    2021-01-07 23:35

    (Re-posting my answer to avoid puppy-socket.)

    Using the compilerOptions.baseUrl property I was able to do the below import. This allowed me to have a complete root-to-expected-path, which helps my code maintainance, and works in any file, independently of the current folder. The below examples will have the src folder of my project as the modules root.

    Important advice: this baseUrl property doesn't affect the entry webpack file (at least for me?), so separate a main file inside the src folder with this example, and run it from the entry (i.e., import { Main } from './src/Main'; new Main;), only once.

    // browser: directory inside src;
    //   * net: A TS file.
    import { URLRequest } from 'browser/net';
    

    tsconfig.json example:

    {
        "compilerOptions": {
            "baseUrl": "./src",
            "module": "commonjs",
            "noImplicitReturns": true,
            "noImplicitThis": true,
            "noUnusedLocals": true,
            "preserveConstEnums": true,
            "removeComments": true,
            "sourceMap": true,
            "strictNullChecks": true,
            "target": "ES6"
        },
    
        "include": [
            "./src/**/*.ts",
            "./src/**/*.d.ts"
        ]
    }
    

    However, it won't directly work with webpack. The same thing must be done at the webpack options. This is how it worked in webpack 2:

    module.exports = {
      ...
      , resolve: {
          ...
          , modules: [ path.join(__dirname, './src') ]
        }
    }
    

提交回复
热议问题