Path of external component template or css when compiling TypeScript to outDir

允我心安 提交于 2019-12-10 17:29:13

问题


When I code Angular 2 apps, my tsconfig.json file contains the following parameter:

"outDir": "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 { }

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).

How to solve this?

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. ;-)


回答1:


Since you want your JavaScript to output to the dist folder, assuming for distribution, then you can create a script that copies the html and css to the dist folder as well. Usually you can run some sort of minification on those files that makes doing that more worthwhile.

Another alternative is to reference these paths relatively through the root directory. So for example, if you have a file /someDir/myfile.ts and /someDir/my.component.html then you can reference my.component.html by doing ../someDir/my.component.html. That will work if /someDir/myfile.ts goes to /dist/myfile.js. The downside to this is that it will probably get annoying to do once your project grows and so I wouldn't recommend it.




回答2:


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']
})


来源:https://stackoverflow.com/questions/37813809/path-of-external-component-template-or-css-when-compiling-typescript-to-outdir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!