My React app uses requires relative to the root of my JS file using Webpack's resolve.root
. I.e. my file structure contains the following:
components
App.react.js
containers
AppContainer.react.js
In AppContainer.react.js, I have:
import App from 'components/App.react';
This works client-side. Now I'm trying to make it isomorphic. If I require AppContainer.react.js in my server.js, it says components/App.react
isn't found. Node is trying to require containers/components/App.react.js
, which doesn't exist. How can I make Node require relative to a given directory?
Edit: My directory structure looks like this:
css/
html/
js/
components/
App.react.js
containers/
AppContainer.react.js
main.js <- requires AppContainer
public/
server/
server.js <- requires AppContainer
Webpack provides reasonable defaults, but it is possible to change the resolving in detail. Have a look at Module Resolution for more explanation of how the resolver works. Configure how modules are resolved. For example, when calling import 'lodash' in ES2015, the resolve options can change where webpack goes to look for 'lodash' (see modules ).
When enabled, webpack would prefer to resolve module requests as relative requests instead of using modules from node_modules directories. Prefer absolute paths to resolve.roots when resolving. Whether to resolve symlinks to their symlinked location. When enabled, symlinked resources are resolved to their real path, not their symlinked location.
Since webpack 3.1.0 context in resolve caching is ignored when resolve or resolveLoader plugins are provided. This addresses a performance regression. Condition names for exports field which defines entry points of a package.
If multiple files share the same name but have different extensions, webpack will resolve the one with the extension listed first in the array and skip the rest.
You could use https://github.com/halt-hammerzeit/universal-webpack. This will let you keep your same webpack config (eg. resolve.root
and any aliases) and additionally help get you moving towards server side rendering. The usage docs give a pretty good example of how to get this up and running.
you can try to use this babel-plugin: babel-plugin-module-resolver
,
then change your .babelrc as follow:
{
"plugins": [
["module-resolver", {
"root": ["."],
"alias": {
"components": "./components"
}
}]
]
}
then you can require your component in your server.js import App from 'components/App.react';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With