Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Ape Fist posted:

TS is such a vastly superior iteration of JS that it's mental.

TS would be a lot better if it went back in time and still supported generation of IIFE. Currently the best it can do with current versions is compiling a bunch of ES5 files with ES6 imports which is :aaa: You still need rollup (my fav) or Webpack (god forbid) or etc to make it work.

It used to work on its own which was awesome.

Adbot
ADBOT LOVES YOU

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Nolgthorn posted:

TS would be a lot better if it went back in time and still supported generation of IIFE. Currently the best it can do with current versions is compiling a bunch of ES5 files with ES6 imports which is :aaa: You still need rollup (my fav) or Webpack (god forbid) or etc to make it work.

It used to work on its own which was awesome.

You CAN still use IIFE if you want, but be prepared to do all your own custom bundling. It's Webpack/Rollup that need ES6 imports.

my bony fealty
Oct 1, 2008

Just learned about Fusebox. Any thoughts? Is it easier/less prone to breaking than Webpack?

AlphaKeny1
Feb 17, 2006

I have a question about testing promises in Angular with Jasmine. Is this the thread for that?

edit: basically I don't understand how to test a promise or wtf I'm doing. I'm still relatively new to all this.

double edit: i figured out how to write my specific spec for this promise but I'm still not really sure how to test promises in general lol

AlphaKeny1 fucked around with this message at 22:40 on Mar 15, 2018

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you
My understanding of this new context API for React is that I no longer need to do Redux/Flux and can use context as a substitute for the Store. Am I misreading this?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
/me checks to see if parsing JSON in Elm still kind of sucks.... :argh:

Well then,

On a scale of 1-10 how much of a pain is it to use TypeScript the first time? Going to be doing a new "smallish" React project for myself, so going a little slow while dealing with it isn't a big deal, but I want to actually enjoy working on this thing.

Any "essential" guides or references you folks who use it regularly can recommend?

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!

Love Stole the Day posted:

My understanding of this new context API for React is that I no longer need to do Redux/Flux and can use context as a substitute for the Store. Am I misreading this?

Depends on your requirements. Having access to the context doesn't mean you're getting unidirectional data flow like you would with flux/redux patterns. The pattern itself is quite useful for making sense of data changes from all over the place in large apps, and redux pretty much forces you to be a little more strict and explicit about it.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Lumpy posted:

/me checks to see if parsing JSON in Elm still kind of sucks.... :argh:

Well then,

On a scale of 1-10 how much of a pain is it to use TypeScript the first time? Going to be doing a new "smallish" React project for myself, so going a little slow while dealing with it isn't a big deal, but I want to actually enjoy working on this thing.

Any "essential" guides or references you folks who use it regularly can recommend?

TS is easier when you're starting a project from scratch than when you're converting an existing project.

How hard it is going to be kind of depends on how familiar you are with C#/Java style languages.

I don't think it's going to be too difficult for you, so maybe a 4 out of 10 difficulty rating.

I can't really remember what I used to learn TS from scratch, but I feel like I used the official docs a lot and then just googled specific questions I had.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Love Stole the Day posted:

My understanding of this new context API for React is that I no longer need to do Redux/Flux and can use context as a substitute for the Store. Am I misreading this?

It can be used as a wholesale replacement, yes. You'll have to figure out your own way of passing around actions and so on, but if you were to keep the entire app's state as the state of the top-level component, and all actions were methods on said component, you can get "redux-like" behavior using only the new Context API. The new stuff actually operates almost exactly like Redux, in a lot of ways. I wonder if FB hiring Dan Abramov had something to do with that.... :ponder:

I might play with new Context stuff in my new project (see above post!)... not sure how best to handle large state trees and async actions etc. but should be pretty easy to get a handle on, maybe. Dealing with multiple contexts looks like a pain, but I've only read a little on it, so I'm not sure if you'd even want to do multiple contexts.

lunar detritus
May 6, 2009


Thermopyle posted:

TS is easier when you're starting a project from scratch than when you're converting an existing project.

How hard it is going to be kind of depends on how familiar you are with C#/Java style languages.

I don't think it's going to be too difficult for you, so maybe a 4 out of 10 difficulty rating.

I can't really remember what I used to learn TS from scratch, but I feel like I used the official docs a lot and then just googled specific questions I had.

I agree with all of this. I did have a harder time but I think it was because I was trying to deal with the Angular 2 beta and trying to grok RxJS at the same time. That learning curve was a wall until it suddenly it all clicked. Now I wish I could use TS for everything.

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.
Yeah Angular 2 offers a good TS experience and also helps you to learn Angular 2.

prom candy
Dec 16, 2005

Only I may dance
Everyone looking to replace Redux seems to forget about the main benefit: the developer experience is top notch

Vincent Valentine
Feb 28, 2006

Murdertime

I switched to Apollo Client + GraphQL to handle state in a personal project because I felt like there was always far too many steps involved with managing state with Redux, especially when it came to really simple state changes.

Definitely a real steep learning curve but now I really can't see myself using anything else.

You query for data with something like:

code:
const UserQuery = gql `
query {
	user {
		realm
		characterName
                userName
                locale
	},
}
`

// Then add it to the components props

const UserInfoCardWithData = graphql(UserQuery)(UserInfoCard);
export default UserInfoCardWithData;
And you're done. It's now in the state cache, is added to the components props and any time the cache changes the props update. You don't even have to define a reducer, just knock off Locale from the query and you no longer get it. If you just want to alter local state and not request data, just put "@client" after "user" in the above query.

It is a thoroughly nice experience.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

prom candy posted:

Everyone looking to replace Redux seems to forget about the main benefit: the developer experience is top notch

By that you mean the experience of developers using it? I've had a breeze using vuex, which uses mutable state, you mute it, it knows you muted it, simple as that. Feels like redux is a lot of boilerplate for ideological reasons.

prom candy
Dec 16, 2005

Only I may dance
I mean specifically the dev tools. Being able to do time travel, see the whole state tree, re-dispatch actions, etc. I am definitely interested in checking out react-apollo, but it uses Redux under the hood doesn't it?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Yes, the redux dev tools are super great and it's difficult to use anything else now.

huhu
Feb 24, 2006
I've got two divs, each 100vw, one representing a grid of projects and another a single project.

code:
|-----| |-----|
|Grid | |Proj |
|     | |-----|
|     |
|     |
|     |
|     |
|-----| 
A user is first presented with the grid. when they click on a project preview, the screen transitions to the right by 100vw and displays the project. However the transition is a wonky. The original issue was that the grid is always longer than a project and if I just transition to the right, there's a good chance there will be an empty screen. So I added a scroll to top of page but that looks really weird. I've tried a bunch of things to try and smooth the transition out but I'm a bit lost. Any suggestions?

Vincent Valentine
Feb 28, 2006

Murdertime

prom candy posted:

I mean specifically the dev tools. Being able to do time travel, see the whole state tree, re-dispatch actions, etc. I am definitely interested in checking out react-apollo, but it uses Redux under the hood doesn't it?

Apollo Client recently moved into 2.0, which uses its own system rather than Redux.

I do have to concede that the Redux dev tools are absolutely top notch, though. AC Dev Tools are incredibly immature by comparison. I deeply miss the ability to see how the state tree evolved over time, but I've gotten by without it.

prom candy
Dec 16, 2005

Only I may dance

huhu posted:

I've got two divs, each 100vw, one representing a grid of projects and another a single project.

code:
|-----| |-----|
|Grid | |Proj |
|     | |-----|
|     |
|     |
|     |
|     |
|-----| 
A user is first presented with the grid. when they click on a project preview, the screen transitions to the right by 100vw and displays the project. However the transition is a wonky. The original issue was that the grid is always longer than a project and if I just transition to the right, there's a good chance there will be an empty screen. So I added a scroll to top of page but that looks really weird. I've tried a bunch of things to try and smooth the transition out but I'm a bit lost. Any suggestions?

Could you set the grid to 100vh and overflow auto so that you're scrolling the div and not the body?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

prom candy posted:

Everyone looking to replace Redux seems to forget about the main benefit: the developer experience is top notch

I love redux dev tools, which is worth staying with Redux for a while regardless, but having to reinvent parts of Redux to replace it has me mostly going "Hmm, why don't I just keep using Redux?" I think the endgame will be a Redux-like thing that creates contexts, and then some sort of context composer so you have reducers for parts of your state tree like Redux does now. So I would expect to see React get something like Redux's store / combineReducers in the near future as sort of a canonical Flux architecture. Or maybe not!

As for Redux boilerplate... do you people not have macros / scripting in your IDEs?? :iiam:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

huhu posted:

I've got two divs, each 100vw, one representing a grid of projects and another a single project.

:words:


Do this:

prom candy posted:

Could you set the grid to 100vh and overflow auto so that you're scrolling the div and not the body?

lunar detritus
May 6, 2009


You haven't seen boilerplate until you have used ngrx. All the redux boilerplate + types + RxJS.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

gmq posted:

You haven't seen boilerplate until you have used ngrx. All the redux boilerplate + types + RxJS.

It's true, but this package has helped me reduce the boilerplate in my angular/rxjs/redux project: https://github.com/cartant/ts-action. I'm using angular-redux instead of ngrx, but I believe it works with both.

smackfu
Jun 7, 2004

AlphaKeny1 posted:

I have a question about testing promises in Angular with Jasmine.

Testing code that generates promises or receives them?

Generates them: add a then block after your call that tests your conditions and then calls the done function.

Received them: use a spy to return a new promise, which you can then test in unresolved, resolved, or error state.

Alternate answer: you should be using Observables not Promises in Angular.

lunar detritus
May 6, 2009


LOOK I AM A TURTLE posted:

It's true, but this package has helped me reduce the boilerplate in my angular/rxjs/redux project: https://github.com/cartant/ts-action. I'm using angular-redux instead of ngrx, but I believe it works with both.

that looks so much better :aaaaa:

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

gmq posted:

that looks so much better :aaaaa:

If it's at all possible I would really recommend switching any code that uses Redux with TS to that library, or something similar. My own Redux code went through three or four iterations before I settled on ts-action. Each of those iterations probably cost me about 10 hours of tedious rewriting, but in the end it was worth it. And the nice thing about Redux is that none of the other code in the app was affected much.

Here's an example of a rewritten actions file: https://gist.github.com/magnusbakken/2380b0384b725113f5e14a9eefb5a5d4

prom candy
Dec 16, 2005

Only I may dance
Whoa this looks really nice, my redux ducks are way too big in my React/Redux/TS project.

I noticed you're importing your other interfaces from <redacted>, where do you actually keep your model interfaces? I've been colocating them with my other Redux stuff but that hasn't really scaled well. Was thinking about creating a types folder that contained each interface in its own file and exported all of them from an index.ts file. I'm a little worried about the potential for circular dependencies but it would be nice to do "import { Author, Book, Library } from 'types'" or something like that.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

prom candy posted:

Whoa this looks really nice, my redux ducks are way too big in my React/Redux/TS project.

I noticed you're importing your other interfaces from <redacted>, where do you actually keep your model interfaces? I've been colocating them with my other Redux stuff but that hasn't really scaled well. Was thinking about creating a types folder that contained each interface in its own file and exported all of them from an index.ts file. I'm a little worried about the potential for circular dependencies but it would be nice to do "import { Author, Book, Library } from 'types'" or something like that.

I'll briefly explain our overall approach. I'd love to hear other people's experiences with Angular and Redux, since it isn't as widespread a combo as React/Redux.

For us, each module has the following structure:
pre:
store/
- actions.ts
- epics.ts
- reducer.ts
- service.ts
- state.ts
The part I called "<redacted>" is a library of interfaces that we've generated based on the server API definition. In our case we've published it as a standalone NPM package, but it could easily live in a folder inside the app instead (which is what we originally did). It's basically exactly what you're talking about, i.e. one file per type and an index.ts that re-exports everything. You shouldn't have issues with circular dependencies as long as you always do local imports inside the interface files and always use the global path from the outside.

Most of the time we just toss data from the server directly into the store, which is possible because the API was very much written with our own client in mind. In cases where we need to transform the data we put extra definitions in the state.ts file and do the conversion in the reducer. The rest of the time the only thing in state.ts is an interface that defines the reducer state for the module. It would probably be fine to join reducer.ts and state.ts together as one file.

Components never interact directly with the store. Actions are dispatched from the service, and store changes are also relayed through the service class. The service.ts for the module from the gist looks like this:

code:
import { Injectable } from "@angular/core";
import { dispatch } from "@angular-redux/store";
import { Observable } from "rxjs";

import { Article } from "<redacted>";
import { IdMap } from "app/common/store";
import { appState } from "app/common/decorators/appstate-select";
import { LoadArticleAction } from "./actions";

@Injectable()
export class ArticlesService {
    @appState(s => s.article.loadedArticles) public readonly loadedArticles: Observable<IdMap<Article>>;
    @appState(s => s.article.loading) public readonly isLoading: Observable<boolean>;

    @dispatch()
    public loadArticle(id: number, schemeId: number, lastModified: string) {
        return new LoadArticleAction({ id, schemeId, lastModified });
    }
}
That @appState decorator is just a helper that lets us write type-safe selections from the store as lambda functions. It's based on the @select decorator from angular-redux. Similarly, the @dispatch decorator automatically dispatches the value returned from the function to the store.

The actual API calls happen in epics.ts. For example, when a LoadArticleAction happens it triggers an epic, which starts an API call and returns either LoadArticleSucceededAction or LoadArticleFailedAction. That looks basically like this (slightly simplified):
code:
export class ArticlesEpics {
    public epics: Array<Epic<Action, AppState>>;

    constructor(private api: ArticleApi) {
        this.epics = [
            this.loadArticle,
            ...
        ];
    }

    public loadArticle = (actions$: ActionsObservable<Action>) => actions$.pipe(
        ofType(LoadArticleAction),
        switchMap(a => this.api.getArticle(a.id)).pipe(
            map(article => new LoadArticleSucceededAction({ article })),
            catchError(r => of(apiFailure(r, LoadArticleFailedAction))),
        )),
    )
}
The ofType rxjs operator is from the ts-action-observable library, and is another way to reduce boilerplate by getting correctly narrowed types inside the observables. The apiFailure thing is another helper function we use for uniform error handling.

We've had to make most of this up as we go, so I wouldn't necessarily recommend all of it to others. It's still a lot of work to do things that could be done with much less ceremony, but hopefully the benefits of Redux will shine through. (Our app is not in production yet.)

Dominoes
Sep 20, 2007

Hey dudes. Do I still need Webpack to make Typescript support imports? When I last checked (a year ago), you could use TSC alone for single-file projects, but multi-file projects required using Webpack, awesome-typescript-loader, sourcemap-loader, webpack config files etc. Search results on the subject are mainly from 2016-2017.

prom candy
Dec 16, 2005

Only I may dance
I'm trying to get an ember 1.x app that I built 3 years ago working locally and holy poo poo what a nightmare. Nothing is compatible with anything. The version of ember-cli doesn't seem to work with versions of node past 0.x, I can't use yarn, the whole thing predates the idea of automatic version locking, and this was my first modern JS application so nothing makes any god drat sense! I almost want to just tell the client that the app is now a delicately preserved artifact and disturbing it ever so slightly could bring the whole thing down. They declined any long-term support or updates so it's just been sitting.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

prom candy posted:

I'm trying to get an ember 1.x app that I built 3 years ago working locally and holy poo poo what a nightmare. Nothing is compatible with anything. The version of ember-cli doesn't seem to work with versions of node past 0.x, I can't use yarn, the whole thing predates the idea of automatic version locking, and this was my first modern JS application so nothing makes any god drat sense! I almost want to just tell the client that the app is now a delicately preserved artifact and disturbing it ever so slightly could bring the whole thing down. They declined any long-term support or updates so it's just been sitting.

prom candy posted:

They declined any long-term support or updates so it's just been sitting.

Problem solved!

prom candy
Dec 16, 2005

Only I may dance
Now they're back and want stuff and have money :( I'm actually leaving this job in a couple weeks but I need to get it into a place so that my co-workers can use it. I've thought about just trying to get it running on Ember 2.x but people are saying that's a bit of an arduous task.

huhu
Feb 24, 2006
I've been playing whack-a-mole for 4 hours now with Webpack/React/Express and I could use some help. I am trying to get dev to run with npm start and prod to run with an express server. I've included my issue first and then the relevant code below. Would really appreciate any help.

Running this:
code:
npm run build && node server.js
Works but running this:
code:
npm start
results in:
code:
Refused to apply style from 'http://localhost:3000/static/css/reset.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Which I'm assuming has something to do with webpack not knowing how to find the static dir. Similarly, I don't understand how the output dirs should be structured between static/ and public/ and do they actually need to be separate?

Finally, do I need index.ejs at all? Express seems to want it but I don't think it's necessary?


File Structure
code:
server.js
webpack.common.js
webpack.dev.js
webpack.prod.js
public/
  index.html
  index.ejs
static/
  css/
    reset.css
  js/
    app.bundle.js
src/
package.json
code:
  "scripts": {
    "start": "NODE_ENV=develop webpack-dev-server --open --hot --inline --config webpack.dev.js",
    "build": "NODE_ENV=production webpack --config webpack.prod.js"
  },
server.js
code:
const express = require('express');
const path = require('path');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/public'));
app.use('/static/js',express.static(path.join(__dirname, 'static/js')));
app.use('/static/css',express.static(path.join(__dirname, 'static/css')));
app.get('/', function(req, res) {
    res.render('index');
});

app.listen(24971);
webpack.common.js
code:
const path = require('path');
var webpack = require('webpack');

var apiHost;

var setupApi = function(){
  console.log(apiHost);
  switch(process.env.NODE_ENV) {
    case 'production':
      apiHost = 'http://eng40.huhu.com/';
      break;
    case 'development':
      apiHost = 'http://localhost:8000/';
      break;
  }
};

setupApi();

module.exports = {
  entry: {
    app: './src/index.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets:[ 'es2015', 'react', 'stage-2' ]
        }
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({__API__: apiHost})
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'static/js')
  }
};
webpack.dev.js
code:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  devtool: 'inline-source-map',
  devServer: {
    publicPath: '/',
    contentBase: "./public",
    port: 3000,
    historyApiFallback: true,
  },
});
webpack.prod.js
code:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  devtool: 'source-map'
});

Sedro
Dec 31, 2008

prom candy posted:

I'm trying to get an ember 1.x app that I built 3 years ago working locally and holy poo poo what a nightmare. Nothing is compatible with anything. The version of ember-cli doesn't seem to work with versions of node past 0.x, I can't use yarn, the whole thing predates the idea of automatic version locking, and this was my first modern JS application so nothing makes any god drat sense! I almost want to just tell the client that the app is now a delicately preserved artifact and disturbing it ever so slightly could bring the whole thing down. They declined any long-term support or updates so it's just been sitting.

I think ember-cli is backwards compatible to 1.x, so you can bring your tooling up to date before touching the app. Upgrading the app might be a lot of effort.

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
I decided to play around with Docker today. I'm sure it's cool but it's darkly humorous to me that within an hour of starting I was using one syntax for the Dockerfile (sentence-case, extension-free), another for docker-compose.yml (standard filename), and a third for .dockerignore (system file). This seems needlessly brittle, especially when it comes to shared values like ports to expose or paths. Do I really just need to copy and paste across these files (and my project files) or is there a better way to glue everything together?

huhu
Feb 24, 2006
Still banging away at various issues. Have perhaps, some more directed questions with regards to React/Express.

Here's my server.js:
code:
const express = require('express');
const path = require('path');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/public'));
app.use('/static/js',express.static(path.join(__dirname, 'static/js')));
app.use('/static/css',express.static(path.join(__dirname, 'static/css')));
app.use('/static/img',express.static(path.join(__dirname, 'static/img')));

app.get('/', function(req, res) {
    res.render('index');
});

app.listen(24971, function(){console.log('Running on port 24971')});
I'm stuck on the part of app.get('/') If I leave it like that, I can visit my React app at huhu.com and browse around it and have the routes change with React-Router. However, if I navigate to huhu.com/foo and refresh, server.js can't find my app. If I change it to app.get('/*') everything works fine for routes like huhu.com/foo and huhu.com however, when I goto huhu.com/foo/bar, which makes a request for the app.js, server.js returns the index page's content inside of app.js instead of the actual code that should be in app.js. What am I doing wrong?

Spraynard Kruger
May 8, 2007

Kobayashi posted:

I decided to play around with Docker today. I'm sure it's cool but it's darkly humorous to me that within an hour of starting I was using one syntax for the Dockerfile (sentence-case, extension-free), another for docker-compose.yml (standard filename), and a third for .dockerignore (system file). This seems needlessly brittle, especially when it comes to shared values like ports to expose or paths. Do I really just need to copy and paste across these files (and my project files) or is there a better way to glue everything together?

I don't think these things usually involve much copying and pasting across them... The Dockerfile defines how to build the image (start with a Node base image, install my npm packages, put app code here, etc). The docker-compose.yml file is an optional, more structured way to store your development settings. And .dockerignore is just like .gitignore, a simple list to define what shouldn't be put inside your Docker image (like your .git folder, maybe your node_modules or Python virtualenv, etc).

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

huhu posted:

Still banging away at various issues. Have perhaps, some more directed questions with regards to React/Express.

Here's my server.js:
code:
const express = require('express');
const path = require('path');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/public'));
app.use('/static/js',express.static(path.join(__dirname, 'static/js')));
app.use('/static/css',express.static(path.join(__dirname, 'static/css')));
app.use('/static/img',express.static(path.join(__dirname, 'static/img')));

app.get('/', function(req, res) {
    res.render('index');
});

app.listen(24971, function(){console.log('Running on port 24971')});
I'm stuck on the part of app.get('/') If I leave it like that, I can visit my React app at huhu.com and browse around it and have the routes change with React-Router. However, if I navigate to huhu.com/foo and refresh, server.js can't find my app. If I change it to app.get('/*') everything works fine for routes like huhu.com/foo and huhu.com however, when I goto huhu.com/foo/bar, which makes a request for the app.js, server.js returns the index page's content inside of app.js instead of the actual code that should be in app.js. What am I doing wrong?

not mine, but do something like this:

https://gist.github.com/ryanoglesby08/1e1f49d87ae8ab2cabf45623fc36a7fe

my bony fealty
Oct 1, 2008

I deployed a node/express/ejs app on my DigitalOcean Ubuntu droplet today and it required a bunch of stuff like configuring an nginx reverse proxy, which drove me insane (wouldn't serve static css or js) until I discovered the problem was a \ instead of /. Derp.

Anyone used the preconfigured node setup DO offers? Does it alleviate the annoyance of having to mess with nginx? I'm thinking it would be wise to get another droplet just for node.

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006

Ugh, what am I missing?

I copied what they had:
code:
const express = require('express');
const path = require('path');
const port = 24971;
const app = express();

app.use(express.static(__dirname + '/dist'));

app.get('*', function (request, response) {
  response.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);
console.log("server started on port " + port);
file structure
code:
index.html
server.js
dist/
  app.bundle.js
index.html
code:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>huhu</title>
    <link rel="stylesheet" href="static/reset.css">
    <link rel="shortcut icon" href="static/favicon.png">
  </head>
  <body>
  <div id="root"></div>
  <script type="text/javascript" src="static/app.bundle.js"></script>
</body>
</html>
Which results in:
code:
app.bundle.js:1 Uncaught SyntaxError: Unexpected token <
Where app.bundle.js has the same contents as index.html above.

Edit:
huhu.com requests the static from huhu.com/static
huhu.com/bar requests the static from huhu.com/static
huhu.com/bar/buzz requests the static from huhu.com/buzz/static

Still not sure why /buzz is getting included.

huhu fucked around with this message at 04:48 on Mar 20, 2018

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply