Module not found: Error: Can't resolve in babel and typecript in monorepo

Viewed 2620

I create a lerna monorepo (nodejs packages) with and I try to compile my typescript files with babel and webpack.

In my project I have two main folders: apps and packages.

I run build in packages/package1 lerna run build. the build script in package1 is webpack.

Inside package1 I have some files:

the webpack.config.js:

 const path = require('path');

 const root = (p) => path.resolve(__dirname, '../..', p);

 const isProd = process.env.NODE_ENV === 'production';
    
    module.exports = {
      entry: {
        app: './app.ts',
      },
    
      output: {
        filename: '[name].js',
      },
    
      target: 'node',
      node: {
        __dirname: false,
      },
    
      module: {
        rules: [
          {
            test: /\.ts$/,
            exclude: /(node_modules|bower_components)/,
            use: {
              loader: 'babel-loader',
            },
          },
        ],
      },
    
      resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        alias: {
          '@packages/*': root('packages/*/src'),
        },
      }
    };

babel.config.js:

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          browsers: ['last 2 versions', 'safari >= 7'],
        },
      },
    ],
    '@babel/preset-typescript',
  ],
  plugins: ['@babel/plugin-proposal-export-default-from'],
};

tsconfig.json

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "module": "esnext",
    "strict": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "target": "esnext",
    "noImplicitAny": false,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "lib": ["esnext", "dom"],
    "types": ["webpack-env", "node","jest"]
  }
}

and in the root of the project I have tsconfig.json:

tsconfig.json:

{
  "compilerOptions": {
    "noEmit": true,
    "strict": true,
    "jsx": "react",
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "removeComments": true,
    "rootDir": ".",
    "baseUrl": ".",
    "paths": {
      "@packages/*": ["packages/*/src"],
      "*": ["node_modules", "packages"]
    }
  },
  "include": ["packages", "jest-dom/extend-expect"],
  "exclude": ["node_modules", "dist"]
}

The problem is, babel/webpack throw an error:

Module not found: Error: Can't resolve '@packages/foo'

of course my files are point to the correct location (index etc).

What could be the problem?

update

I add alias section in webpack, but its not works:

 alias: {
      '@packages/*': root('packages/*/src'),
    },
0 Answers
Related