My application has a directory structure more or less like this:
src-program/
- contains frontend code includingpackage.json
andwebpack.config.js
src-server/
- contains backend code including a differentpackage.json
and.babelrc
shared/foo.js
- is JavaScript code that is needed by both the frontend and the backend
All code uses ES2015 syntax and thus is transpiled using Babel.
For the frontend the "transpilation" is done during the Webpack build by using the babel-loader.
For the backend it is done on-the-fly by babel-register.
shared/foo.js
requires other modules, that are found in the package.json
files of both the frontend and the backend.
Due to how NodeJS/Webpack resolve modules, the shared module isn't found normally.
For Webpack I solved this in a somewhat hacky way using this configuration:
resolve: {
root: __dirname,
fallback: [
__dirname + "/../shared",
__dirname + "/node_modules"
],
extensions: ['', '.js', '.jsx']
},
The first fallback
makes sure that the "shared" module is resolved and the second fallback
makes sure that modules required by the shared module are still resolved to the frontend node_modules
directory.
This allows including the shared module as simple as this:
import * as foo from 'foo';
However, I'm having difficulties to make the backend (ie. NodeJS) resolve the shared module the same way.
I tried with app-module-path, which makes foo.js
resolve, but then the file is either not processed by Babel or additional Babel modules like transform-runtime
(indirectly needed by foo.js
) cannot be resolved since they reside in src-server/node_modules
...
I could probably work around the problem by pre-transpiling the code instead of using babe-register
but it all doesn't feel right anyway.
So, what is a good way to share code between a Webpack build and the NodeJS server process?