I'd like to configure some webpack aliases to point to some of my folders (not to a lib in node_modules).
Here is a simple example:
var path = require('path');
module.exports = {
webpack: function (config) {
config.resolve.alias = {
'components': path.resolve('./components'),
};
return config
}
}
However, if I try to import a component in a page e.g:
import { NavBar } from 'components';
I get the following error:Error: Cannot find module 'components'
Any idea how to get next to play nice with an alias like this?
This is bit tricky and you need more support from us because or SSR.
We've a ongoing PR here: https://github.com/zeit/next.js/pull/767 which add a alias functionality.
I'm looking for the same answer. I've checked out your suggestion @arunoda, but it didn't seem to resolve the problem.
Now we do this like this:
@arunoda my use case is a bit closer to @thisbejim than the example used there. Rather than override certain things in production or development, i just want to be able refer to my components with
import foo from "components/some-component"
rather than some combination of
../../../components/components
is the suggested way to do that still to create a server.js file but then drop the if(!dev) line?
EDIT: It doesn't seem to work i still get
```
[1] { Error: Cannot find module 'components/common-boot'
[1] at Function.Module._resolveFilename (module.js:470:15)
[1] at Function.Module._load (module.js:418:25)
[1] at Module.require (module.js:498:17)
[1] at require (internal/module.js:20:19)
[1] at Object.
[1] at Module._compile (module.js:571:32)
[1] at Object.Module._extensions..js (module.js:580:10)
[1] at Module.load (module.js:488:32)
[1] at tryModuleLoad (module.js:447:12)
[1] at Function.Module._load (module.js:439:3) code: 'MODULE_NOT_FOUND' }
``
Do I have to create a server.js to achieve this?
The best option is to go with babel-plugin-module-alias
Has anyone gotten this to work? I cannot get this aliasing stuff to work so I can eliminate the horrible paths in the imports, ie
import { someFunction } from 'lib/util'
rather than
import { someFunction } from '../../lib/util'
I have tried babel-plugin-module-alias, babel-plugin-webpack-alias, setting webpack resolve.modules all to no avail.
I've been using module-alias successfully, just make sure you add the changes from their documentation to your .babelrc file.
Found my issue, everything is working great now. Thanks!
There's an example for doing this now https://github.com/zeit/next.js/tree/master/examples/with-absolute-imports
I'm sorry, I should have made this example when I got mine working.
@zentuit no worries 馃槃 馃憤
Most helpful comment
There's an example for doing this now https://github.com/zeit/next.js/tree/master/examples/with-absolute-imports