问题描述
当我编写Angular 2应用程序时,我的tsconfig.json
文件包含以下参数:
When I code Angular 2 apps, my tsconfig.json
file contains the following parameter:
"outDir": "dist"
表示TypeScript-to-JavaScript编译会将生成的文件存储在dist
文件夹中.
meaning the TypeScript-to-JavaScript compilation will store generated files in the dist
folder.
我的问题是,当我尝试使用具有组件相对路径,如下所示:
My problem is when I try using components which have an external template or CSS file and which use component-relative paths, like so:
@Component({
moduleId: module.id,
selector: 'my-cmp',
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
export class MyComponent { }
浏览器尝试从已转译的JavaScript文件所在的文件夹(dist
下)加载.html
和.css
文件.但是这些文件仅存在于原始文件夹(原始TypeScript文件所在的文件夹)中.
The browser tries to load the .html
and .css
files from the same folder where the transpiled JavaScript file is located — under dist
. But these files only exist in the original folder (where the original TypeScript file is located).
如何解决这个问题?
注意:如果我删除moduleId: module.id
并且使用绝对路径(例如, app/my-cmp/my.component.html
,但这不是我想要的. ;-)
Note: The code works if I remove moduleId: module.id
and I use absolute paths, e.g. app/my-cmp/my.component.html
, but it's not what I want. ;-)
推荐答案
module.id只是生成的JavaScript文件的路径(例如, http://localhost:8080/dist/app/my.component.js ).您可以使用module.id.replace('dist','')省略dist以完成所需的操作:
module.id is just the path of generated JavaScript file (e.g., http://localhost:8080/dist/app/my.component.js). You can omit dist with module.id.replace('dist', '') to accomplish what you want:
@Component({
moduleId: module.id.replace('dist', ''),
selector: 'my-cmp',
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
这篇关于将TypeScript编译为outDir时外部组件模板或CSS的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!