简体   繁体   中英

Use javaScript file in angular 5 project

I am building a web application using Angular 5 and nodejs with express. 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. The solutions that I have found didn't worked for me.

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

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:

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.

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

In production mode it will serve the files in the folder /backend/dist_frontend by default (apart from the backend routes (/api)). I use a build process (GitLab CI) to move the files I need to the respective place...

I finally find a solution. It would be necessary to modify the tsconfig.json:

tsconfig.json

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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