Noel De Martin
Noel De Martin

Reputation: 2857

Ionic 2: tsconfig.json modifications not working in order to prevent long relative paths

I started an ionic 2 project and one of the few things I don't like is the relative paths. I read some documentation from typescript and I modified the tsconfig.json file, and seems like the modifications I do are not taking any effect in the ionic app (but are working in typescript).

I learned how typescript works from the documentation: http://www.typescriptlang.org/docs/handbook/module-resolution.html

I validated that my changes to tsconfig.json are correct since calling "tsc --traceResolution" tells me the resolution is working. But once I launch the ionic app I get the "Cannot find module" error.

Example

In order to reproduce the issue, create a brand new ionic 2 project, modify tsconfig.json by adding the following to compilerOptions:

"baseUrl": "./src",

Then create the file src/foo.ts with the contents:

export class Foo {}

finally add the following to app.module.ts:

import { Foo } from 'foo';
new Foo();

As far as I understand that should work, it doesn't and for it to work it is necessary to have the following (which I want to avoid):

import { Foo } from '../foo';
new Foo();

Upvotes: 3

Views: 2183

Answers (1)

studds
studds

Reputation: 1405

You need to override the default webpack.config.js to be able to resolve files relative to the baseUrl.

In order to use a custom webpack configuration file with ionic, this should be added to the package.json of the project:

{
    ...
    "config": { "ionic_webpack": "./webpack.config.js" },
    ...
}

And then in ./webpack.config.js:

var path = require('path');
var useDefaultConfig = require('@ionic/app-scripts/config/webpack.config.js');

// to match the basePath in tsconfig.json, we add src as a module path, which means we can use
// module style imports for our code. Without this, an import that typescript thinks is valid, like
// `import { Foo } from 'foo';` will fail at build time
useDefaultConfig.dev.resolve.modules.push(path.resolve('src'));
useDefaultConfig.prod.resolve.modules.push(path.resolve('src'));


/**
 * export the update ionic webpack configs (this still includes both dev & prod webpack configs)
 */
module.exports = function () {
  return useDefaultConfig;
};

Upvotes: 3

Related Questions