简体   繁体   中英

How to load bundles with angular-cli?

I must be missing something extremely simple here, because I don't understand how anyone can have a functioning angular-cli app without the ability to do the following...

Context

I have an Angular 2 app with an express.js backend acting as an API. I have switched from webpack to angular-cli to bundle my files as it offers easy Ahead-Of-Time compilation.

What I didn't expect was angular-cli is so opinionated, it even requires me to keep an index.html file inside the angular app directory in my repository (I had previously kept it in /views for express.js to send to clients).

Problem

I am struggling to see how I can load the outputted JS bundles from angular-cli if I have node.js server. Consider the following angular-cli.json snippet:

"apps": [
{
    "root": "app",
    "outDir": "public/dist",
],

Both my bundle.js files and my index.html will be outputted in public/dist . This means I have to update my node.js routes to change:

// Root
app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/../views/index.html'));
});

to:

// Root
app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/../public/dist/index.html'));
});

Now the problem is that my public/dist/index.html file has a <base href="/"> tag, and the following generated script tags:

<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script>

Well, obviously when I run my node.js server, those above bundles won't be found because they don't exist at the base href's location. There is no /inline.bundle.js , because it's located at /public/dist/inline.bundle.js . So, how can I ever load my frontend app?

I don't this will work, as it expect an absolute path, not relative.

res.sendFile(path.join(__dirname + '/../public/dist/index.html'));


You should point in a relative way all the dist server to / from the express folder, something like:

app.use('/', express.static('../public/dist'));

app.get('*', (req, res) => {
    res.sendFile('index.html', { root: '../public/dist' });
});

I handle this kind of problems in a different way. I never send a file using sendFile , instead I only send JSON data.

Sending a file is suitable for traditional non-SPA applications. Sending JSON data is suitable for modern SPA applications.

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