nrwl / nx

Smart Monorepos · Fast CI
https://nx.dev
MIT License
23.48k stars 2.34k forks source link

Migrate NX 16 to NX 17 - TypeError: Cannot read properties of undefined (reading 'assets') #27911

Open joshuaballas opened 1 month ago

joshuaballas commented 1 month ago

Current Behavior

I am in the process of upgrading from NX 14 to NX 19. I've been incrementally upgrading to prevent large issues. After upgrading from v16 to v17, config is no longer being populated in my custom-webpack.config.js file and throwing this error:

C:\Projects\myproject\node_modules\@nx\webpack\src\utils\with-nx.js:18
            assets: options.assets
                            ^

TypeError: Cannot read properties of undefined (reading 'assets')

The project.json and custom-webpack.config.js can be found below.

Expected Behavior

I expected that config would be passed into my webpack file like all of the previous versions.

GitHub Repo

No response

Steps to Reproduce

  1. Run nx run myproject:pre-build:production

Nx Report

Node   : 20.17.0
   OS     : win32-x64
   npm    : 9.6.2

   nx (global)        : 19.7.2
   nx                 : 17.3.2
   @nx/js             : 17.3.2
   @nx/jest           : 17.3.2
   @nx/linter         : 17.3.2
   @nx/eslint         : 17.3.2
   @nx/workspace      : 17.3.2
   @nx/cypress        : 17.3.2
   @nx/devkit         : 17.3.2
   @nx/eslint-plugin  : 17.3.2
   @nx/react          : 17.3.2
   @nrwl/tao          : 17.3.2
   @nx/web            : 17.3.2
   @nx/webpack        : 17.3.2
   typescript         : 5.3.3

Failure Logs

When I use nrwlConfig(config, {})
TypeError: Cannot read properties of undefined (reading 'assets')

When I use nrwlConfig(config, context)
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

ERROR in main
Module not found: Error: Can't resolve './src' in 'C:\Projects\myproject'
resolve './src' in 'C:\Projects\myproject'
  using description file: C:\Projects\myproject\package.json (relative path: .)
    Field 'browser' doesn't contain a valid alias configuration
    using description file: C:\Projects\myproject\package.json (relative path: ./src)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        C:\Projects\myproject\src doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        C:\Projects\myproject\src.js doesn't exist
      .jsx
        Field 'browser' doesn't contain a valid alias configuration
        C:\Projects\myproject\src.jsx doesn't exist
      .ts
        Field 'browser' doesn't contain a valid alias configuration
        C:\Projects\myproject\src.ts doesn't exist
      .tsx
        Field 'browser' doesn't contain a valid alias configuration
        C:\Projects\myproject\src.tsx doesn't exist
      as directory
        C:\Projects\myproject\src doesn't exist

Package Manager Version

npm 9.6.2

Operating System

Additional Information

project.json

{
  "name": "myproject",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "apps/myproject/src",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "dependsOn": ["pre-build"],
      "options": {
        "commands": [
          "npx workbox-cli generateSW ./apps/myproject/workbox-config.js",
          "node moveScript.js"
        ],
        "parallel": false
      }
    },
    "pre-build": {
      "executor": "@nx/webpack:webpack",
      "outputs": ["{options.outputPath}"],
      "defaultConfiguration": "production",
      "options": {
        "compiler": "babel",
        "outputPath": "dist/apps/myproject",
        "index": "apps/myproject/src/index.html",
        "baseHref": "/",
        "main": "apps/myproject/src/main.tsx",
        "polyfills": "apps/myproject/src/polyfills.ts",
        "tsConfig": "apps/myproject/tsconfig.app.json",
        "assets": [
          "apps/myproject/src/favicon.ico",
          "apps/myproject/src/assets",
          "apps/myproject/src/manifest.json",
          "apps/myproject/src/data",
          "apps/myproject/src/data/translations",
          "apps/myproject/src/web.config",
          "apps/myproject/src/fonts"
        ],
        "styles": ["apps/myproject/src/styles.css"],
        "scripts": [],
        "webpackConfig": "apps/myproject/custom-webpack.config.js"
      },
      "configurations": {
        "development": {
          "extractLicenses": false,
          "optimization": false,
          "sourceMap": true,
          "vendorChunk": true
        },
        "production": {
          "fileReplacements": [
            {
              "replace": "apps/myproject/src/environments/environment.ts",
              "with": "apps/myproject/src/environments/environment.prod.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "namedChunks": false,
          "extractLicenses": true,
          "vendorChunk": false
        }
      }
    },
    "serve": {
      "executor": "@nx/webpack:dev-server",
      "defaultConfiguration": "development",
      "options": {
        "buildTarget": "myproject:pre-build",
        "hmr": true
      },
      "configurations": {
        "development": {
          "buildTarget": "myproject:pre-build:development"
        },
        "production": {
          "buildTarget": "myproject:pre-build:production"
        }
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "outputs": ["{options.outputFile}"]
    },
    "test": {
      "executor": "@nx/jest:jest",
      "outputs": ["{workspaceRoot}/coverage/apps/myproject"],
      "options": {
        "jestConfig": "apps/myproject/jest.config.ts"
      }
    }
  },
  "tags": []
}
/* eslint-disable import/extensions */
/* eslint-disable @typescript-eslint/no-var-requires */
const nrwlConfig = require('@nx/react/plugins/webpack.js')
const { merge } = require('webpack-merge')
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')

module.exports = (config, context) => {
  nrwlConfig(config, {}) // Ensure Nx configurations are applied first

  // Check if we're in development mode
  const isDevelopment = context.configurationName === 'development'

  return merge(config, {
    output: {
      publicPath: '',
    },
    resolve: {
      extensions: ['.js', '.jsx', '.ts', '.tsx'], // Handle JavaScript and TypeScript files
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/, // Handle TypeScript files
          use: {
            loader: 'ts-loader',
            options: {
              transpileOnly: true, // Optional: improves build speed by skipping type checking
            },
          },
          exclude: /node_modules\/(?!yoga-layout)/, // Exclude all node_modules except yoga-layout
        },
        {
          test: /\.svg$/, // Add rule for handling SVGs
          oneOf: [
            {
              issuer: /\.[jt]sx?$/, // If the SVG is imported in a JS/TS file
              use: ['@svgr/webpack'], // Import SVGs as React components
            },
            {
              type: 'asset', // Handle SVGs as URL/file when imported in non-JS files (CSS, etc.)
            },
          ],
        },
        {
          test: /\.js$/,
          enforce: 'pre',
          use: [
            {
              loader: 'source-map-loader',
              options: {
                filterSourceMappingUrl: (url, resourcePath) => {
                  if (/html5-qrcode/i.test(resourcePath)) {
                    return false
                  }

                  return true
                },
              },
            },
          ],
        },
      ],
    },
    plugins: [
      isDevelopment && new ReactRefreshWebpackPlugin(), // Enable React Fast Refresh only in development mode
    ].filter(Boolean), // Remove false values from the plugins array
  })
}
jaysoo commented 3 weeks ago

Can you retry with latest Nx as there has been several changes since v17.

If you stick with v17, you can try using withNx({ assets: [...] }) in your webpack config.

github-actions[bot] commented 2 weeks ago

This issue has been automatically marked as stale because no results of retrying on the latest version of Nx was provided within 7 days. It will be closed in 21 days if no results are provided. If the issue is still present, please reply to keep it active. If the issue was not present, please close this issue. Thanks for being a part of the Nx community! 🙏