Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webpack Loader unable to resolve alias paths #811

Closed
utkarshk384 opened this issue Aug 2, 2021 · 1 comment
Closed

Webpack Loader unable to resolve alias paths #811

utkarshk384 opened this issue Aug 2, 2021 · 1 comment
Labels
bug report 🦗 Issue is probably a bug, but it needs to be checked bundler: webpack 📦 Issue is related to webpack bundler cat: modules aliasing 🔗 Issue related to modules aliasing cat: performance 🚀 Issue is related to performance needs: complete repro 🖥️ Issue need to have complete repro provided

Comments

@utkarshk384
Copy link

utkarshk384 commented Aug 2, 2021

Environment

System:
  OS: macOS 11.4
Binaries:
  Node: 14.17.0
  npm: 6.14.13
npmPackages:
 "@babel/core": "^7.14.8",
    "@linaria/babel-preset": "^3.0.0-beta.4",
    "@linaria/core": "^3.0.0-beta.4",
    "@linaria/react": "^3.0.0-beta.7",
    "@linaria/shaker": "^3.0.0-beta.7",
    "@linaria/webpack-loader": "^3.0.0-beta.7",
    "@storybook/addon-actions": "^6.3.6",
    "@storybook/addon-essentials": "^6.3.6",
    "@storybook/addon-links": "^6.3.6",
    "@storybook/preset-scss": "^1.0.3",
    "@storybook/react": "^6.3.6",
    "babel-loader": "^8.2.2",
    "lodash": "^4.17.21",
    "mini-css-extract-plugin": "^2.1.0",
     "sass": "^1.36.0",
    "sass-loader": "10.1.1",
    "tsconfig-paths-webpack-plugin": "^3.5.1",
    "typescript": "^4.0.3",
  webpack: 4

Description

So I am trying to build a UI Library with storybook and for that, I thought of using Linaria. However, after getting started with linaria I ran into this issue of typescript paths not being resolved properly by the linaria-webpack-loader. I am specifically using the @linearia/webpack-loader and not the @linaria/webpack-loader4. Here is the error that I'm getting while I try to import using path alias:

Module build failed (from ./node_modules/@linaria/webpack-loader/lib/index.js):
Error: /Volumes/Storage/coding/JavaScript/UI/packages/button/style.ts: An unexpected runtime error occurred during dependencies evaluation: 
/Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:147
		if (err) throw err;
		         ^

Error: Can't resolve '@UI/core' in '/Volumes/Storage/coding/JavaScript/UI/packages/button'
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:209:21
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/Volumes/Storage/coding/JavaScript/UI/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/Volumes/Storage/coding/JavaScript/UI/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:27:1)
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js:67:43
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/Volumes/Storage/coding/JavaScript/UI/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:28:1)
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js:30:40
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/Volumes/Storage/coding/JavaScript/UI/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/Resolver.js:285:5
    at eval (eval at create (/Volumes/Storage/coding/JavaScript/UI/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/forEachBail.js:30:14
    at /Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js:56:16
    at SyncAsyncFileSystemDecorator.stat (/Volumes/Storage/coding/JavaScript/UI/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js:15:12)

The code:

import { css } from "@UI/utils"
import { Colors } from "@UI/core"

import type { Config } from "./types"
import type { DefaultThemeType } from "@UI/types"
import { useEffect, useMemo, useState } from "react"
import { useTheme } from "@UI/theme"

As for the code, if I change the import from @UI/core to ../core then everything works as expected until the next import from @UI. I also noticed that the first import (@UI/utils) gets imported without any issues. Maybe because it's just a re-export of the css function that is inside the @linaria/core library

I also confirm that I can import using the same path alias with other files that are not linked with @linaria/webpack-loader

The folder structure:

.
├── .storybook
│   ├── main.js
│   └── preview.tsx
├── packages
│   ├── types
│   │   └── index.ts
│   ├── utils
│   │   └── index.ts
│   ├── core
│   │   └── index.ts
│   └── button
│       └── style.ts
├── tsconfig.json
└── package.json

The tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": ".",
    "strictPropertyInitialization": false,
    "noImplicitAny": true,
    "paths": {
      "@UI/*": ["packages/*"],
    }
  },
  "include": [
    ".storybook/*.tsx", 
    "packages"  
  ]
}

The webpack Config at ./.storybook directory

webpackFinal: (config, {configType}) => {
    config.resolve.plugins = config.resolve.plugins || [];
    config.resolve.plugins.push(
      new TsconfigPathsPlugin({
        configFile: path.resolve(__dirname, "../tsconfig.json"),
      })
    );


    config.module.rules.push({
      test: /\.ts$/,
      include: /packages/,
      use: [
        {
          loader: 'babel-loader',
          options: {
            presets: [
              require.resolve('@babel/preset-env'),
              require.resolve('@babel/preset-typescript'),
              require.resolve('@linaria/babel-preset'),
            ],
          },
        },
        {
          loader: '@linaria/webpack-loader',
          options: {
            babelOptions: {
              presets: [
                require.resolve('@babel/preset-env'),
                require.resolve('@babel/preset-typescript'),
                require.resolve('@linaria/babel-preset'),
              ],
            },
          },
        },
      ],
    });
    return config
  },

Reproducible Demo

I tried to reproduce a minimal example in code sandbox but the process of setting up webpack and all the loaders related to it was too cumbersome. However here is the link for it.

@utkarshk384 utkarshk384 added bug report 🦗 Issue is probably a bug, but it needs to be checked needs: complete repro 🖥️ Issue need to have complete repro provided needs: triage 🏷 Issue needs to be checked and prioritized labels Aug 2, 2021
@github-actions github-actions bot added bundler: webpack 📦 Issue is related to webpack bundler cat: performance 🚀 Issue is related to performance cat: modules aliasing 🔗 Issue related to modules aliasing and removed needs: triage 🏷 Issue needs to be checked and prioritized labels Aug 2, 2021
@utkarshk384
Copy link
Author

utkarshk384 commented Aug 2, 2021

For anyone who is trying to figure out why their path is not being resolved.

So firstly, linaria doesn't support tsconfig-paths-webpack-plugin at all as mentioned here. Therefore, you need to first yarn add babel-plugin-module-resolver and then head over to your webpack.config.js and then update as follows:

{
        loader: '@linaria/webpack-loader',
        options: {
          babelOptions: {
            plugins: [
              [
                "babel-plugin-module-resolver", 
                { 
                  "root": ["./src/components"], //the value mentioned in the path section of the `tsconfig.json based on your CWD` 
                  extensions: [".tsx", ".ts"], 
                  alias: aliases //The important part!!
                }
              ]
            ],
            presets: [
              require.resolve('@babel/preset-env'),
              require.resolve('@babel/preset-typescript'),
              require.resolve('@linaria/babel-preset'),
            ],
          },
        },
      }

The aliases is the manual addition of the aliases in tsconfig.json. For ease for anyone looking to add their aliases here is a simple function to add those:

const getDirectories = source =>
  fs.readdirSync(source, { withFileTypes: true })
    .filter(dirent => dirent.isDirectory())
    .map(dirent => dirent.name)
    
const getAlias = (alias, path) => {
  const aliases = {}
  const dirs = getDirectories(path)

  dirs.forEach(dir => aliases[`${alias}/${dir}`] = `${path}/${dir}`)

  return aliases
}

//For Example 

const aliases = getAlias("@Component", path.resolve(__dirname, ".src/component") // Will return a object of aliases and their paths

Thanks to @geakstr for the solution(#663 (comment))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug report 🦗 Issue is probably a bug, but it needs to be checked bundler: webpack 📦 Issue is related to webpack bundler cat: modules aliasing 🔗 Issue related to modules aliasing cat: performance 🚀 Issue is related to performance needs: complete repro 🖥️ Issue need to have complete repro provided
Projects
None yet
Development

No branches or pull requests

1 participant