Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack Aliases in Node JS Server code

I'm building an isomorphic React/React-Router/Redux/Webpack application and I'm attempting to implement server side rendering.

My directory looks like:

/client
    /actions
    /components
    /containers
/server
    /server.js

In my webpack config, I have aliases set up for all the folders inside client:

var path_base = path.resolve(__dirname, '..');
const resolve = path.resolve;
const base = function() {
  var args = [path_base];
  args.push.apply(args, arguments);
  return resolve.apply(resolve,args);
};
const resolve_alias = base.bind(null, 'src/client');
const aliases = [
  'actions',
  'components',
  'constants',
  'containers',
  'middleware',
  'reducers',
  'routes',
  'store',
  'styles',
  'utils',
  'validation'
];

so that inside the code that gets bundled by webpack, I can do:

import { Widget } from 'components'; 

and that import gets resolved by webpack.

Now in my server code, in order to do the rendering, I have to import some of my client files, like routes/index.js. The problem I'm running into when I import my routes file, it's using a webpack alias to another file, say components or containers so naturally, the node js require system can't resolve it.

How do I fix something like that? I looked at this question and it talks about essentially setting up the same aliases that exist in webpack with mock-require. But then the issue becomes that my routes file imports all my components which then all import things like stylesheets, images, etc. Should I then be using something like webpack-isomorphic-tools?

The guides I've been looking at (this for example) are all great at showing how server side rendering is accomplished but none of them really talk about how to resolve all the requires and whatnot.

like image 495
barndog Avatar asked Jan 08 '16 18:01

barndog


People also ask

What is alias in NodeJS?

module-alias modifies the internal Module. _nodeModulePaths so that the current directory behaves as the node_modules directory. Steps to follow: Create aliases of directories and register custom module paths in NodeJS using module-alias. Let's first install module-alias.

Can you use webpack for Node?

Webpack provides a Node. js API which can be used directly in Node. js runtime.


1 Answers

After battling with this issue for 2 days I settled on babel-plugin-webpack-alias. What you need to do to resolve paths with that is:

  1. $ npm install --save-dev babel-plugin-webpack-alias
  2. Add the plugin to your .babelrc
  3. Add the aliases to your webpack.config (make sure you use path.join())
  4. Refer to this post if you have problems loading styles

The other option I tried was universal-webpack but I found it to be a bit verbose. If you want to see roughly how the whole server-side loading works, you can check out this video.

like image 95
Vlady Veselinov Avatar answered Sep 25 '22 01:09

Vlady Veselinov