I am trying to have a namespace for my app to work as a module, and import my components using this namespace and limit the use of relative path.
Although, even though I followed the webpack documentation for alias here: http://webpack.github.io/docs/configuration.html#resolve-alias
I can't make it to work.
This is how my resolve object looks like:
resolve: {
root: path.resolve(__dirname),
alias: {
myApp: './src',
},
extensions: ['', '.js', '.json', '.jsx']
}
path.resolve(__dirname) resolves /Users/Alex/Workspace/MyAppName/ui/
I import my file that way in the file /Users/Alex/Workspace/MyAppName/ui/src/components/Header/index.jsx:
import { myMethod } from 'myApp/utils/myUtils';
I get the following error during the build:
ERROR in ./src/components/Header/index.jsx
Module not found: Error: Cannot resolve module 'myApp/utils/myUtils' in /Users/Alex/Workspace/MyAppName/ui/src/components/Header
# ./src/components/Header/index.jsx 33:19-56
I also tried with modulesDirectories but it doesn't work either.
Do you have any idea what is wrong?
Resolving the alias to the absolute path should do the trick:
resolve: {
alias: {
myApp: path.resolve(__dirname, 'src'),
},
extensions: ['', '.js', '.jsx']
}
Check this webpack resolve alias gist with a simple example.
Another solution to limit the number of relative paths is to add your ./src folder as root instead of aliasing it:
resolve: {
root: [path.resolve('./src')],
extensions: ['', '.js', '.jsx']
}
Then you will be able to require all folders inside ./src as if they where modules. For example, assuming you have the following directory structure:
.
├── node_modules
├── src
│ ├── components
│ └── utils
you would be able to import from components and utils like this:
import Header from 'components/Header';
import { myMethod } from 'utils/myUtils';
Something like having an alias for each folder inside ./src.
This might be obvious to many but if you, like me, have spent too much time trying to figure out why it suddenly does not work when moving from Windows or Mac to Linux then check casing in the paths...
Me and everyone else on the project are using Windows or Mac but at home I dual boot ubuntu which I enjoy using. On cloning our code and running webpack i got a whole lot of Cannot resolve module... errors. I spent more time than I'd like to admit searching for some obscure error in node, npm, webpack or anything until I noticed the paths of the failing modules were something like #app/Shared/settings.js and the require was require('#app/shared/settings'). Windows doesn't care so everything was fine all until I started working on linux. As it turned out problem was not with webpack, node or anything else so that's probably why I didn't find anyone suggesting that this could be the problem.
Hope this saves some time for someone. Or maybe I'm just dumb, I don't know.
Most of the time it depends on your project folder structure. If your webpack file is inside a folder then make sure you handle it accordingly
.
├── node_modules
├── src
│ ├── components
│ └── config/webpack.config.js
modules.exports = {
resolve: {
extensions: ['.js', '.jsx'],
alias: {
Components: path.resolve(__dirname, '../src/components/'),
}
},
...
resolve: {
...
}
}
Also it often happens that we name our folder as "source" but use "src" in path.
Darn! that copy paste has taken alot of my debug time
Hope this helps someone who is facing such issues due to the above reasons.
I got the same error. Finnaly I found the problem was that I wrote resolve twice. And the second resolve override the previous one.
My code is like this:
modules.exports = {
resolve: {
extensions: ['.js', '.jsx'],
alias: {
Components: path.resolve(__dirname, 'src/components/'),
}
},
...
resolve: {
...
}
}
More help can be found in Webpack Doc
I use without next syntax :
resolve: {
alias: {
Data: __dirname + '/src/data'
},
extensions: ['.js', '.jsx', '.json']
}
import points from 'Data/points.json';
In my case, I wanted to alias mobx, so that any import of mobx would always return the same instance, regardless of whether the import call was from my main app, or from within one of the libraries it used.
At first I had this:
webpackConfig.resolve.alias = {
mobx: path.resolve(root, "node_modules", "mobx"),
};
However, this only forced imports of mobx from my app's own code to use the alias.
To have it work for the library's import calls as well, I had to do:
webpackConfig.resolve.alias = {
mobx: path.resolve(root, "node_modules", "mobx"),
"LIBRARY_X/node_modules/mobx": path.resolve(root, "node_modules", "mobx"),
};
It's odd, because I'm pretty sure just having the mobx alias used to work for both contexts before, but now it apparently doesn't (Webpack v4.41.2).
Anyway, the above is how I solved it. (In my case, I needed it to prevent two mobx instances from being used as that breaks things, and LIBRARY_X was symlinked using npm-link, so I couldn't delete/unify the secondary mobx folder itself)
Related
I'm trying to set up an alias in my app built with create-react-app .
I don't use typescript . The IDE (WebStorm) sees my alias paths. Shows the contents of a folder. But when I refresh the page, I get the error:
Module not found: Error: Can't resolve '#HomePage/HomePage' in 'C:\Users\ASUS\WebstormProjects\spnew\client\src'
I'm going to add the HomePage component which is in the HomePage folder.
My way:
1) I made an eject
2) Created a 'jsconfig.json' file in the root directory with react
{
"compilerOptions": {
"baseUrl": ".",
paths: {
"#HomePage/*": ["./src/pages/HomePage/*"]
}
},
"exclude": ["node_modules"]
}
p.s. tried without #, tried to remove './'
p.s.s. after adding this file, the IDE reacts to:
import {...} from "#HomePage/"; tells you what files are in this folder.
3) The auto-generated webpack.config.js file has very few features.
On the Internet they write what needs to be done like this:
modules.exports = {
resolve: {
extensions: ['.js', '.jsx'],
alias: {
Components: path.resolve(__dirname, '../src/components/'),
}
},
...
resolve: {
...
}
}
I already have over 700 lines in this file!
But the structure is the same. I found module.exports which has nested resollve which has nested alias. And added a line with the path.
It looks like this:
alias: {
HomePage: path.resolve(__dirname, "../src/pages/HomePage"),
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
}
p.s. I tried to write the path './' '../' and without it.
When importing, I get the same error!
Compiled with problems:X
ERROR in ./src/routes.js 9:0-46
Module not found: Error: Can't resolve '#HomePage/HomePage' in 'C:\Users\ASUS\WebstormProjects\spnew\client\src'
I would like to use an alias in VUE.JS in a Laravel 5.8 project to import css and js I have in my module.
webpack.mix.js
mix.webpackConfig({
resolve: {
alias: {
'alias': path.resolve(
__dirname,
'~myModule/src'
)
}
}
});
In my VUE App.js I would like import the css folder and I wrote:
resources/js/app.js
// css files
import 'alias/lib/css'
// js files
import 'alias/lib/script'
But I'm wrong something becouse the alias is not resolved:
ERROR in ./resources/js/app.js
Module not found: Error: Can't resolve 'alias/lib/css' in...
Can you help me to fix the issue?
After so many attempts I got the issue. The code was good but I was missing to load the webpack.mix.js properly:
From Laravel Mix documentation:
The webpack.mix.js file is your entry point for all asset compilation. Think of it as a light configuration wrapper around Webpack. Mix tasks can be chained together to define exactly how your assets should be compiled.
But if you are using npm run watch it is not (re)loaded before to compile new changed assets. This means:
if you are in watch mode (npm run watch) exit and restart it to load new updated webpack.config.js if you changed it.
Finally it worked! And it resolve new alias properly!
Here the final config I used in webpack.config.js:
mix.webpackConfig({
resolve: {
alias: {
'aliasName': path.resolve(
__dirname,
'node_modules/MyModule/src/'
)
}
}
});
Another alternative is:
mix.webpackConfig({
resolve: {
modules: [
'node_modules'
],
alias: {
'aliasName' : 'MyModule/src/'
}
}
});
Then in my Vue component (or in vue app.js, just in case)
<template>
<myModule-component></myModule-component>
</template>
require('aliasName/lib/css'); // to load full css directory
require('aliasName/lib/script'); // to load full js directory
import MyModuleComponent from 'aliasName/widgets/MyModuleComponent.vue'
...
export default {
...
components: {
'myModule-component': MyModuleComponent
}
I am currently setting up my project to be a bit cleaner, especially in the frontend part with references.
In hindsight I noticed that I was very generous with the folder structure for my frontend files and ended up with lots of layers. That's why I decided to look into what webpack can do for this case, and found out about the alias functionality.
This is how I set it up:
resolve: {
alias: {
components: path.resolve(__dirname, "Scripts/Views/Components"),
data: path.resolve(__dirname, "Scripts/Data"),
definitions: path.resolve(__dirname, "Scripts/Definitions"),
helper: path.resolve(__dirname, "Scripts/Helper"),
scripts: path.resolve(__dirname, "Scripts"),
views: path.resolve(__dirname, "Scripts/Views"),
},
extensions: [".tsx", ".ts", ".js", ".jsx"],
modules: ["node_modules"]
}
As you can see, I created alias' for various folders here.
This is my folder structure:
Now, let's hop into e.g. the LoginDialog.tsx. Here I am trying to import like this:
import { IErrorAttachedProperty } from "definitions/formHelper";
However, all I end up with here is an error that no module could be found this way.
What am I doing wrong here?
If it is of any significance - The webpack.config.js resides in the same directory as the Scripts folder.
you have to config tsconfig.json for typescript
"baseUrl": "./",
"paths": {
"components/*": [
"./src(or any other path)/Scripts/Views/Components"
]
},
here is nice example ts alias
Ok, so to avoid confusion for others I'm posting my solution/findings:
Yes, you can just use tsconfig.json without needing resolve/alias in Webpack. You should just do it once with Typescript setup.
EDIT: Nope, turns out you do need resolve/alias section in webpack.config.js. Typescript will be happy without it, but then you will get Webpack errors when it builds. Do both to make it work.
TIP: Make sure the paths you provide in the paths section of tsconfig.json are relative to the baseUrl entry point. Don't make them relative to the tsconfig.json file, baseUrl is like the project root for the non-relative module imports defined with paths.
From Typescript docs, absolute modules names (import * from package-a) are relative to baseUrl ~ https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url
All module imports with non-relative names are assumed to be relative to the baseUrl.
Relative modules (import * from ./packages) are just from current file as stated:
Note that relative module imports are not impacted by setting the baseUrl, as they are always resolved relative to their importing files.
So if you have:
./packages
./package-a
./package-b
./index.ts
./tsconfig.json
Your tsconfig.json would look like:
{
"compilerOptions": {
"baseUrl": "./packages",
"paths": {
"package-a/*": [ "./package-a/*" ],
},
},
"include": [
"./packages/**/*"
]
}
Then your webpack.config.json would look like:
{
resolve: {
alias: {
'package-a': path.resolve(__dirname, 'packages/package-a/'),
}
},
}
Then you can import from index.ts like this:
import { pkgAThing } from 'package-a';
// or
import { otherPkgAThing } from 'package-a/dir/dir`;
Which is alternative to relative style:
import { pkgAThing } from './packages/package-a`;
I'm currently working on project, which depends partialy on 'bower only' dependencies and I need somehow to add bower_components module to Webpack 2 bundle. How can I do it? Documentation from previous version doesn't work and bower-webpack-plugin is outdated. I'm using Webpack#2.2.1.
I added this code to webpack.config.js:
resolve: {
extensions: ['.js', '.jsx'],
modules: ['bower_components', 'node_modules']
}
But unfortunately this doesn't work.
Use current version of documentation
Correct resolving of path to bower_components with path module had helped me. Maybe it will helps you.
Webpack2 can be used with bower with resolving options, you can read more here: https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options
A simple example of webpack.config.js resolving a bower.json file:
module.exports = {
entry: './file.js',
output: {
filename: 'my-first-webpack.bundle.js'
},
resolve: {
modules: [ "bower_components"],
descriptionFiles: ["bower.json"]
}
};
I'm still confused how to resolve module paths with webpack. Now I write:
myfile = require('../../mydir/myfile.js')
but I'd like to write
myfile = require('mydir/myfile.js')
I was thinking that resolve.alias may help since I see a similar example using { xyz: "/some/dir" } as alias then I can require("xyz/file.js").
But if I set my alias to { mydir: '/absolute/path/mydir' }, require('mydir/myfile.js') won't work.
I feel dumb because I've read the doc many times and I feel I'm missing something.
What is the right way to avoid writing all the relative requires with ../../ etc?
Webpack >2.0
See wtk's answer.
Webpack 1.0
A more straightforward way to do this would be to use resolve.root.
http://webpack.github.io/docs/configuration.html#resolve-root
resolve.root
The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.
In your case:
webpack config
var path = require('path');
// ...
resolve: {
root: path.resolve('./mydir'),
extensions: ['', '.js']
}
consuming module
require('myfile')
or
require('myfile.js')
see also: http://webpack.github.io/docs/configuration.html#resolve-modulesdirectories
For future reference, webpack 2 removed everything but modules as a way to resolve paths. This means root will not work.
https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options
The example configuration starts with:
{
modules: [path.resolve(__dirname, "app"), "node_modules"]
// (was split into `root`, `modulesDirectories` and `fallback` in the old options)
resolve.alias should work exactly the way you described, so I'm providing this as an answer to help mitigate any confusion that may result from the suggestion in the original question that it does not work.
a resolve configuration like the one below will give you the desired results:
// used to resolve absolute path to project's root directory (where web pack.config.js should be located)
var path = require( 'path' );
...
{
...
resolve: {
// add alias for application code directory
alias:{
mydir: path.resolve( __dirname, 'path', 'to', 'mydir' )
},
extensions: [ '', '.js' ]
}
}
require( 'mydir/myfile.js' ) will work as expected. If it does not, there must be some other issue.
If you have multiple modules that you want to add to the search path, resolve.root makes sense, but if you just want to be able to reference components within your application code without relative paths, alias seems to be the most straight-forward and explicit.
An important advantage of alias is that it gives you the opportunity to namespace your requires which can add clarity to your code; just like it is easy to see from other requires what module is being referenced, alias allows you to write descriptive requires that make it obvious you're requiring internal modules, e.g. require( 'my-project/component' ). resolve.root just plops you into the desired directory without giving you the opportunity to namespace it further.
In case anyone else runs into this problem, I was able to get it working like this:
var path = require('path');
// ...
resolve: {
root: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')],
extensions: ['', '.js']
};
where my directory structure is:
.
├── dist
├── node_modules
├── package.json
├── README.md
├── src
│ ├── components
│ ├── index.html
│ ├── main.js
│ └── styles
├── webpack.config.js
Then from anywhere in the src directory I can call:
import MyComponent from 'components/MyComponent';
I have resolve it with Webpack 2 like this:
module.exports = {
resolve: {
modules: ["mydir", "node_modules"]
}
}
You can add more directories to array...
My biggest headache was working without a namespaced path. Something like this:
./src/app.js
./src/ui/menu.js
./node_modules/lodash/
Before I used to set my environment to do this:
require('app.js')
require('ui/menu')
require('lodash')
I found far more convenient avoiding an implicit src path, which hides important context information.
My aim is to require like this:
require('src/app.js')
require('src/ui/menu')
require('test/helpers/auth')
require('lodash')
As you see, all my app code lives within a mandatory path namespace. This makes quite clear which require call takes a library, app code or a test file.
For this I make sure that my resolve paths are just node_modules and the current app folder, unless you namespace your app inside your source folder like src/my_app
This is my default with webpack
resolve: {
extensions: ['', '.jsx', '.js', '.json'],
root: path.resolve(__dirname),
modulesDirectories: ['node_modules']
}
It would be even better if you set the environment var NODE_PATH to your current project file. This is a more universal solution and it will help if you want to use other tools without webpack: testing, linting...
If you're using create-react-app, you can simply add a .env file containing
NODE_PATH=src/
Source: https://medium.com/#ktruong008/absolute-imports-with-create-react-app-4338fbca7e3d
Got this solved using Webpack 2 :
resolve: {
extensions: ['', '.js'],
modules: [__dirname , 'node_modules']
}
This thread is old but since no one posted about require.context I'm going to mention it:
You can use require.context to set the folder to look through like this:
var req = require.context('../../mydir/', true)
// true here is for use subdirectories, you can also specify regex as third param
return req('./myfile.js')
Simply use babel-plugin-module-resolver:
$ npm i babel-plugin-module-resolver --save-dev
Then create a .babelrc file under root if you don't have one already:
{
"plugins": [
[
"module-resolver",
{
"root": ["./"]
}
]
]
}
And everything under root will be treated as absolute import:
import { Layout } from 'components'
For VSCode/Eslint support, see here.
I didn't get why anybody suggested to include myDir's parent directory into modulesDirectories in webpack, that should make the trick easily:
resolve: {
modulesDirectories: [
'parentDir',
'node_modules',
],
extensions: ['', '.js', '.jsx']
},