离子2:tsconfig.json修改不起作用以防止长相对路径

时间:2016-12-05 08:33:33

标签: typescript ionic2

我开始了一个离子2项目,其中一件我不喜欢的事情就是相对路径。我从typescript中读到了一些文档,并修改了tsconfig.json文件,看起来我所做的修改在离子应用程序中没有任何影响(但是在打字稿中工作)。

我从文档中了解了typescript的工作原理:http://www.typescriptlang.org/docs/handbook/module-resolution.html

我验证了我对tsconfig.json的更改是正确的,因为调用" tsc --traceResolution"告诉我解决方案正在发挥作用。但是一旦我启动离子应用程序,我就会得到"找不到模块"错误。

示例

为了重现这个问题,创建一个全新的离子2项目,通过将以下内容添加到compilerOptions来修改tsconfig.json:

"baseUrl": "./src",

然后使用以下内容创建文件src / foo.ts:

export class Foo {}

最后将以下内容添加到app.module.ts:

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

据我所知,这应该有效,但它没有工作,因此必须有以下内容(我想避免):

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

1 个答案:

答案 0 :(得分:3)

您需要覆盖默认的webpack.config.js才能解析相对于baseUrl的文件。

为了使用带有离子的自定义webpack配置文件,应将其添加到项目的package.json中:

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

然后在./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;
};