Reputation: 31
i set up a project using webpack, react and typescript. I am now trying to use aliases for imports, which works fine for the most part. However, i can't make importing css files to work with aliases.
I added the following part to my webpack.config.json
...
resolve: {
extensions: ["", ".ts", ".tsx", ".js", ".json", "css", ".scss"],
alias: {
BaseComponents: path.resolve(__dirname, "src", "BaseComponents"),
Pages: path.resolve(__dirname, "src", "Pages"),
Styles: path.resolve(__dirname, "src", "Styles"),
},
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: "babel-loader",
exclude: /node_modules/,
},
{
test: /\.(css)$/,
use: ["style-loader", "css-loader"],
},
],
},
...
and the following part to the tsconfig.json
...
"paths": {
"BaseComponents/*": ["./src/BaseComponents/*"],
"Pages/*": ["./src/Pages/*"],
"Styles/*": ["./src/Styles/*"],
},
...
Importing other react components and normal functions works as expected.
When i write
import "../Styles/test.css";
it works fine. But using the alias
import "Styles/test.css";
doesn't work, even though the ide doesn't complain and intellisense works when typing in the path.
The error is
ERROR in ./src/BaseComponents/App.tsx 3:0-25 Module not found: Error: Can't resolve 'Styles/test.css'
Does anyone know how to solve this?
Thank you.
Upvotes: 2
Views: 1339
Reputation: 396
I have a similar setup, had the same issue when I was trying to build the project but everything worked fine in the IDE, etc. I was able to solve it by installing babel-plugin-module-resolver
and configure it as following:
"plugins": [
...,
[
"module-resolver",
{
"alias": {
"@components": "./src/components"
}
}
]
]
Upvotes: 0