简体   繁体   English

在Angle 5项目中使用JavaScript文件

[英]Use javaScript file in angular 5 project

I am building a web application using Angular 5 and nodejs with express. 我正在使用Angular 5和带有Express的nodejs构建一个Web应用程序。 As both the frontend and the backend are going to run in the same server I want to use my backend javascript functions in the frontend. 由于前端和后端都将在同一服务器上运行,因此我想在前端中使用后端javascript函数。 The solutions that I have found didn't worked for me. 我找到的解决方案不适用于我。

appController.js appController.js

var createApp = function (appData) {
    console.log("App created")
}

exports.createApp = createApp;

This is the backend file that I want to use in the front. 这是我想在前端使用的后端文件。

Javascript files don't need to export things when used in the front-end. 在前端使用Javascript文件时,无需导出内容。 Most of the time, they use global variables. 大多数时候,它们使用全局变量。 You should go with that. 你应该去那。

To add it to your project, add it anywhere you want, and in your Typescript, you can simply use 要将其添加到项目中,请将其添加到所需的任何位置,并且可以在Typescript中使用

declare var myGlobalVariable: any;

// ...

myGlobalVariable.createApp();

I did a similar thing. 我做了类似的事情。 I have a frontend with Angular 5 and a backend serving an API via Express: 我有一个使用Angular 5的前端和一个通过Express服务API的后端:

If you want to run your Angular frontend and your NodeJS backend on the same server you'll have to build your Angular project and serve the built files with your Express server. 如果要在同一台服务器上运行Angular前端和NodeJS后端,则必须构建Angular项目并使用Express服务器提供已构建的文件。

I think I found a tutorial on that – but I can't find it right now... Instead maybe have a look at my code for the backend: https://github.com/saitho/ngHashi/blob/next/backend/src/index.ts 我想我找到了关于它的教程-但是我现在找不到它了……也许可以看看我的后端代码: https : //github.com/saitho/ngHashi/blob/next/backend /src/index.ts

In production mode it will serve the files in the folder /backend/dist_frontend by default (apart from the backend routes (/api)). 在生产模式下,它将默认提供/ backend / dist_frontend文件夹中的文件(后端路由(/ api)除外)。 I use a build process (GitLab CI) to move the files I need to the respective place... 我使用构建过程(GitLab CI)将所需的文件移动到各个位置...

I finally find a solution. 我终于找到了解决方案。 It would be necessary to modify the tsconfig.json: 有必要修改tsconfig.json:

tsconfig.json tsconfig.json

{
  compilerOptions: {
       .....
       allowJS: true,
       ......
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM