My Objective
I created a dummy module called my-component that exports a single class named Something. The module is located in the app/modules/ directory. Currently, I am attempting to access it from app/app.js using the import syntax:
import { Something } from 'my-component';
Expectation: Given my current Webpack configuration (shown below), I expected this import statement to work as intended.
Actual Outcome: Instead, I encountered the following error message:
ERROR in [default] /<project_dir>/app/app.ts:1:26
Cannot find module 'my-component/Something'.
Attempted Solutions
I can confirm that the module itself is correctly defined because:
- I was able to import it using a relative path:
import { Something } from './my-component'
- It imported successfully when moved to
node_modules/my-component
.
The issue only arises when trying to import the module without a relative path from the modules/ directory. This leads me to believe that the problem lies within my Webpack configuration.
Configuration Details
As illustrated below, I have listed two directories under resolve.root:
project_dir/app
project_dir/node_modules
Interestingly, while it manages to resolve from node_modules
, it fails to do so from app
.
Project Structure
Webpack
project_dir/
├── app/ context, resolve.root
│ ├── app.ts
│ └── my-component/
│ ├── index.ts
│ └── Something.ts
├── webpack.config.js
├── node_modules/ resolve.root
│ ├── ...
│ ├── ...
│ └── ...
└── dist/
└── ...
app/app.ts
import { Something } from 'my-component/Something';
app/my-component/index.ts
export { Something } from './Something'
app/my-component/Something.ts
class Something {
}
export { Something };
webpack.config.js
var path = require('path'),
ROOT = path.resolve(__dirname, '.');
module.exports = {
context: path.resolve(ROOT, 'app'),
entry: 'app.ts',
output: {
path: path.resolve(ROOT, 'dist'),
filename: '[name]-[hash].js'
},
module: {
loaders: [
{ test: /\.ts$/, loader: 'awesome-typescript' }
]
},
resolve: {
root: [
path.resolve(__dirname, 'app'),
path.resolve(__dirname, 'node_modules')
],
extensions: [
'', '.ts', '.js'
]
}
};
EDIT Corrected the project layout.