angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Add project source dir as a module

Open filipesilva opened this issue 10 years ago • 50 comments

It would be very useful to be able to address components via a relative path starting at the project root. A way to do this is to consider the project root as a special project, as if it was inside of node_modules as far as resolution is concerned.

Such a design greatly reinforces the 'app as a library' idea, and plays nice with most module loading scheme.

A proposed name is @app but configurable via angular-cli.json, where app is the project prefix specified in ng new --prefix app (this exists already and defaults to app).

Example:

// instead of 
import { something } from '../../../../../../../shared/something';
// we could do
import { something } from '@app/shared/something';

This would also work for CSS preprocessors.

Such implementation would address https://github.com/angular/angular-cli/issues/865 and also greatly reduce the need for https://github.com/angular/angular-cli/issues/900.

filipesilva avatar Jul 27 '16 16:07 filipesilva

This two steps allowed the proposed @app thing works

I just submited a pull request about it: https://github.com/angular/angular-cli/pull/2210

  • changed the tsconfig.json, adding:
"baseUrl": ".",
 "paths": {
      "@app/*": [
        "app/*"
      ],
      "app/*": [
        "app/*"
      ]
    }

and then changed the resolve on webpack-build-common.js

var aliasConfig = {
    'app': path.join(appRoot, 'app')
  };
  aliasConfig['@' + appConfig.prefix] = path.join(appRoot, 'app');

....
resolve: {
            extensions: ['', '.ts', '.js'],
            root: appRoot,
             alias: aliasConfig,
        },

abner avatar Sep 19 '16 04:09 abner

For full tsconfig.json paths support, change the resolve object located at https://github.com/angular/angular-cli/blob/master/packages/angular-cli/models/webpack-build-common.ts#L38 to:

    resolve: {
      extensions: ['', '.ts', '.js'],
      root: appRoot,
      plugins: [
        new atl.TsConfigPathsPlugin({
          tsconfig: path.resolve(appRoot, appConfig.tsconfig)
        })
      ]
    },

Note the addition of the atl.TsConfigPathsPlugin.

Also, depending on the future implementation of the ngc integration, this may become unnecessary and/or incompatible in the future.

clydin avatar Sep 19 '16 13:09 clydin

@clydin Thanks for that, and @abner for triggering the additional attention. I am running @clydin's changes locally and it works exactly as advertised for ng serve. For ng test I had to add:

// insert at line 5
const atl = require('awesome-typescript-loader');
// ...
// replace near line 14
resolve: {
      extensions: ['', '.ts', '.js'],
      root: appRoot,
      plugins: [
        new atl.TsConfigPathsPlugin({
          tsconfig: path.resolve(appRoot, appConfig.tsconfig)
        })
      ]
    },

To https://github.com/angular/angular-cli/blob/master/packages/angular-cli/models/webpack-build-test.js. Works so far. I leave it up to those who know about the interplay between the various affected systems to say if this is a good idea or not :~)

ggranum avatar Sep 19 '16 14:09 ggranum

Great! I just updated the PR #2210 to use the TsConfigPathsPlugin as sugested.

abner avatar Sep 20 '16 06:09 abner

Also, depending on the future implementation of the ngc integration, this may become unnecessary and/or incompatible in the future.

@clydin Why, unnecessary? Are ngc already support tsconfig's path?

ValeryVS avatar Sep 27 '16 20:09 ValeryVS

awesome-typescript-loader is not compatable with becoming ngc update. The best approach, that I see is using webpack config's resolve {alias: ...} https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options

  • read tsconfig.json and get path object
  • read agular-cli.json and get css paths (for sass imports)
  • join these paths and add to webpack config's resolve {alias: ...}

ValeryVS avatar Sep 27 '16 20:09 ValeryVS

Fixed by https://github.com/angular/angular-cli/pull/2470. We're not looking at also doing the CSS preprocessors right now, but will look at it later.

filipesilva avatar Oct 06 '16 15:10 filipesilva

can some one consolidate a guide on how to config and use this?

applemate avatar Feb 17 '17 08:02 applemate

I'm still running into this using the latest release of the cli. The path resolves using tsc, but not ng.

❯ tsc --traceResolution | grep @app
======== Resolving module '@app/types/element.type' from '/path/to/my/project/src/app/components/library/element-list/element-list.component.ts'. ========
'baseUrl' option is set to '/Users/wayne/src/github.com/overhq/over-cms', using this value to resolve non-relative module name '@app/types/element.type'
'paths' option is specified, looking for a pattern to match module name '@app/types/element.type'.
Module name '@app/types/element.type', matched pattern '@app/*'.
======== Module name '@app/types/element.type' was successfully resolved to '/path/to/my/project/src/app/types/element.type.ts'. ========
❯ ng build
Hash: 3c4a820798b36084d24b
Time: 12929ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 231 kB {4} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 260 kB {3} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 15.2 kB {4} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.51 MB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in /path/to/my/project/src/app/components/library/element-list/element-list.component.ts (2,23): Cannot find module '@app/types/element.type'.)

Here are my versions:

{
  "dependencies": {
    "@angular/common": "2.4.9",
    "@angular/compiler": "2.4.9",
    "@angular/core": "2.4.9",
    "@angular/forms": "2.4.9",
    "@angular/http": "2.4.9",
    "@angular/platform-browser": "2.4.9",
    "@angular/platform-browser-dynamic": "2.4.9",
    "@angular/router": "3.4.9",
    "@types/moment-timezone": "^0.2.34",
    "angular2-notifications": "0.4.53",
    "core-js": "2.4.1",
    "ie-shim": "0.1.0",
    "ionicons": "3.0.0",
    "less": "2.7.2",
    "lodash": "^4.17.4",
    "moment": "2.17.1",
    "moment-timezone": "^0.5.11",
    "ng2-bs3-modal": "0.10.4",
    "ng2-select": "1.2.0",
    "pace-progress": "1.0.2",
    "rxjs": "5.2.0",
    "zone.js": "0.7.8"
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-rc.1",
    "@angular/compiler-cli": "2.4.9",
    "@types/jasmine": "2.5.38",
    "@types/node": "7.0.8",
    "codelyzer": "2.0.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "3.2.0",
    "karma": "1.4.1",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "5.1.0",
    "ts-node": "2.1.0",
    "tslint": "4.5.1",
    "typescript": "2.2.1"
  }
}

Here's my .angular-cli.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "project"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "plugins",
        "dist",
        "static",
        "bootstrap",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "mobile": false,
      "styles": [
        "styles.css"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "local": "environments/environment.local.ts",
        "dev": "environments/environment.dev.ts",
        "staging": "environments/environment.staging.ts",
        "prod": "environments/environment.prod.ts",
        "dynamic": "environments/environment.dynamic.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "files": "src/**/*.ts",
      "project": "src/tsconfig.app.json"
    },
    {
      "files": "src/**/*.spec.ts",
      "project": "src/tsconfig.spec.json"
    },
    {
      "files": "e2e/**/*.ts",
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {
      "inlineTemplate": false,
      "spec": true
    }
  }
}

wayneashleyberry avatar Mar 13 '17 15:03 wayneashleyberry

Does anyone know how to resolve this issue? Property paths in tsconfig doesn't help at all. Actually, it helps on .ts compilation phase, but it fails in WebPack then.

antonberezan avatar Mar 14 '17 07:03 antonberezan

@antonberezan I actually found using the default cli setup, this kinda works out of the box now. You can import {ElementService} from 'app/services/element.service'; automagically.

wayneashleyberry avatar Mar 14 '17 07:03 wayneashleyberry

@antonberezan I actually found using the default cli setup, this kinda works out of the box now. You can import {ElementService} from 'app/services/element.service'; automagically.

To me is giving me cannot find module.

ekaitzht avatar Apr 13 '17 12:04 ekaitzht

@ekaitzht I summarized some of the issues I had getting named paths to work here. The project I link in there is a working example - not claiming it's a quality working example, but it uses named paths and it loads, runs tests and the libraries it emits don't break AoT for consuming projects.

ggranum avatar Apr 13 '17 12:04 ggranum

Just split up my app.module in to features modules, implement lazy loading, etc, it is quite time consuming to change the paths basically you had to do it twice in components and in spec files - nightmare. Looking forward for absolute path feature in CLI a lot.

kuncevic avatar Apr 24 '17 01:04 kuncevic

To make the current version of vscode pick up the settings, you'll need to add a workspace settings file

@clydin Is there a similar solution for WebStorm/PHPStorm?

Update: Found out the cause and the solution, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000158164-Angular-CLI-with-paths-in-tsconfig

undeletable avatar May 30 '17 17:05 undeletable

After struggling by searching over internet n trying to understand what exactly problem and trying different troubleshooting option, I came to know baseUrl and Path how works together

Note: This solution is for Angular Cli 1.x . Not sure about other tool,

If you use baseUrl:"." like below it works in VScode but not while compiling

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": ".",
    "paths": {
      "@myproject/*": ["src/app/*"]
    }    
}

As far my understanding and my working app and checked in angular aio code, I suggest use as baseUrl:""src like below

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "paths": {
      "@myproject/*": ["app/*"],
      "testing/*": ["testing/*"]
    }    
}

By having base URL as source(src directory), compiler properly resolves modules.

I hope this helps to people resolve this kind of issue.

VirajNimbalkar avatar Jul 27 '17 10:07 VirajNimbalkar

I don't get how something so simple can be so hard to achieve.

Fortunately this guide worked for me.

In tsconfig.json

"compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "."
}

in webpack.config.js

module.exports = {
  "resolve": {
    "extensions": [
      ".ts",
      ".js"
    ],
    "modules": [
      "./node_modules",
      ".",
    ]
}

Now let's imagine you have the next project structue.

/** 
 * Assuming the following project structure
 *   /src
 *     /app
 *       /services/file1.js
 *       /models/file2.js
 *     /node_modules
 *     .webpack.config.js
 *     tsconfig.json
 */

If you wanna import the file example 2 from example1, from now on you can use

import { AnythingIWant} from 'src/app/models/file2';

Zeioth avatar Aug 21 '17 14:08 Zeioth

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
        "app": [
            "src/app/*"
        ]
    },
    "include": ["src/**/*"],
    "exclude": []
}

... and it should be all good.

atte-backman avatar Oct 09 '17 10:10 atte-backman

Here's how I handled it: in tsconfig.json

"compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@directives/*": ["app/shared/directives/*"],
      "@services/*": ["app/shared/services/*"],
      "@models/*": ["app/shared/models/*"],
      "@assets/*": ["assets*"],
      "@components/*": ["app/components/*"]
    },
...

Example: import { ShoppingItem } from "@models/shopping-item.model";

ppozniak avatar Oct 13 '17 14:10 ppozniak

They removed the above mentioned solution with awesome-typescript-loader and they're now using AotPlugin: https://github.com/angular/angular-cli/commit/f9a7c01602546dea6c92adb165a5c437689c41b4#diff-3c07f218821da114292666210f358440

If I use something like import { AppComponent } from 'app/app.component' in app.module.ts then tooling doesn't work and editor complains about TS2307: Cannot find module 'app/app.component'.

If I put

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

into tsconfig.json

then the editor reports an error inside app.component.ts:

Angular: Component 'AppComponent' is not included in a module and will not be available inside a template. Consider adding it to an NgModule declaration.

darkbasic avatar Oct 17 '17 13:10 darkbasic