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

Global CSS cannot be imported from within node_modules. #440

Closed
w3ichen opened this issue Dec 19, 2022 · 12 comments
Closed

Global CSS cannot be imported from within node_modules. #440

w3ichen opened this issue Dec 19, 2022 · 12 comments

Comments

@w3ichen
Copy link
Contributor

w3ichen commented Dec 19, 2022

I upgraded from monaco-languageclient==0.13.1-next.9 to monaco-languageclient==4.0.1, and it's failing to run.

The issue appears to come from monaco-editor's actionbar.js file where this CSS file is imported: import './actionbar.css';
This is currently an open issue on monaco-editor: microsoft/monaco-editor#886

I was following the react-client example by @kaisalmen. I'm wondering how they got it to work since monaco-editor isn't importing for me. Any help would be greatly appreciated, thanks!

Code

import { CloseAction, ErrorAction, MessageTransports, MonacoLanguageClient } from 'monaco-languageclient';

Error

(node:33782) [DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
error - ./node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Location: node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.js

My NextJS App Versions

    "@monaco-editor/react": "^4.4.6",
    "monaco-editor": "^0.34.1",
    "monaco-languageclient": "^4.0.1",
    "next": "^12.0.7",
    "react": "^17.0.2",
@kaisalmen
Copy link
Collaborator

Hi @w3ichen vite does the magic in the react client example, but you seem to have a webpack issue. We have a webpack verification example since a couple of month that checks monaco-editor/monaco-languageclient client example can be build with webpack and that the output can be used. You find it here:
https:/TypeFox/monaco-languageclient/tree/main/packages/verify/webpack

Best idea for a way forward: Test our webpack example and compare your build instructions to ours.

@w3ichen
Copy link
Contributor Author

w3ichen commented Dec 23, 2022

Thanks for your help @kaisalmen.
I tried the webpack example and it does work, but I was unable to reproduce the fix in NextJS.
However, I did find another work around here.
I upgraded NextJS to "next": "^13.1.0" and enabled the new appDir feature from inside next.config.js:

module.exports = {
  experimental: {
    appDir: true,
  }
};

Thanks for this amazing library, I finally got it working.
Happy holidays 🎄, I will close this issue now!

@w3ichen w3ichen closed this as completed Dec 23, 2022
@chaitanya71998
Copy link

Thanks for your help @kaisalmen. I tried the webpack example and it does work, but I was unable to reproduce the fix in NextJS. However, I did find another work around here. I upgraded NextJS to "next": "^13.1.0" and enabled the new appDir feature from inside next.config.js:

module.exports = {
  experimental: {
    appDir: true,
  }
};

Thanks for this amazing library, I finally got it working. Happy holidays christmas_tree, I will close this issue now!

@w3ichen Greetings
Have you created any app directory apart from these two steps?

  • updating the next to version 13
  • adding experimental appDir property

I am also integrating monaco language client to a monaco react app created in next js. But blocked got stuck at this issue

can you share what steps have you done to solve this issue?

thanks in advance

@w3ichen
Copy link
Contributor Author

w3ichen commented Dec 31, 2022

Hi @chaitanya71998 , these are the steps I did:

  1. Upgrade to NextJS 13: https://nextjs.org/docs/upgrading#upgrading-from-12-to-13
npm i next@latest react@latest react-dom@latest eslint-config-next@latest
# or
yarn add next@latest react@latest react-dom@latest eslint-config-next@latest
  1. In next.config.js, enable the experimental appDir: https://beta.nextjs.org/docs/upgrade-guide#migrating-from-pages-to-app
  experimental: {
    appDir: true,
  },
  1. Create a new directory in root called app, and add a file called layout.tsx:
export default function Layout({ children }: React.PropsWithChildren<unknown>) {
  return (
    <html>
      <body>{children}</body>
    </html>
  );
}

Doing this, I was able to import monaco-languageclient without getting "Global CSS cannot be imported from within node_modules.". However, I'm still resolving some console errors and breaking changes from upgrading these packages. I don't think I completely implemented the appDir feature, there seems to be a lot more details in the nextjs docs.

@chaitanya71998
Copy link

Thanks @w3ichen
Have you tried configuring webpack related changes to implement. as I got not to update and go with 13 version of next js.
Also if i try to update to 13 next js version there are some dependencies blocking to update.
Screenshot from 2023-01-02 11-10-44

@kaisalmen Can you share what things that could be done exactly if we want to configure in next.config.js to resolve CSS issue?

@w3ichen
Copy link
Contributor Author

w3ichen commented Jan 2, 2023

@chaitanya71998 I did get some blocking dependencies when updating. Mostly, it was some packages not supporting the latest react version. I just did npm install <package> --force.
And then in my package.json, I added version overrides:

{

  "dependencies": {

  },
  "overrides": {
    "next-auth": {
      "react": "$react",
      "react-dom": "$react-dom"
    },
  }
}

Unfortunately, upgrading all the packages and using appDir was the only way I could get the latest version of monaco-languageclient to work in nextjs. I spent a long time looking at other solutions out there, such as the webpack configs you mentioned, but none of them seemed to work for me.

@w3ichen w3ichen reopened this Jan 2, 2023
@chaitanya71998
Copy link

chaitanya71998 commented Jan 2, 2023

@w3ichen Greetings,
Got it. I am also exploring to do it in Next @12. I got an approach from dev.io platform, and It worked to a xtend but from there i got this raised with this issue.
Screenshot from 2023-01-02 12-36-26

Did you know regarding this?
cc: @kaisalmen

@chaitanya71998
Copy link

chaitanya71998 commented Jan 2, 2023

Hi @w3ichen and @kaisalmen I used this next.config.js and the server started without any errors. But after using monco language client as import i was getting the below error.
error:
image

For reference:

// package.json
dependencies:{
		"monaco-editor": "^0.34.1",
		"monaco-languageclient": "4.0.1",
		"next": "^12.1.0",
		"next-transpile-modules": "9.0.0",
		"vscode": "npm:@codingame/[email protected]",
		"vscode-ws-jsonrpc": "2.0.1",
		}
"resolutions": {
		"vscode-languageserver-types": "3.17.2"
	}
// next.config.js
//@ts-nocheck
const withTM = require("next-transpile-modules")([
	// `monaco-editor` isn't published to npm correctly: it includes both CSS
	// imports and non-Node friendly syntax, so it needs to be compiled.
	"monaco-editor",
])
module.exports = withTM({
	reactStrictMode: true,
	swcMinify: true,
	webpack: webpackConfig => {
		// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
		webpackConfig.experiments.topLevelAwait = true
		// eslint-disable-next-line @typescript-eslint/no-unsafe-return
		return webpackConfig
	},
	eslint: {
		// Warning: This allows production builds to successfully complete even if
		// your project has ESLint errors.
		ignoreDuringBuilds: true,
	},
})
// Monaco editor file
import Spinner from "@components/Spinner"
import Editor from "@monaco-editor/react"
import { CloseAction, ErrorAction, MessageTransports, MonacoLanguageClient, MonacoServices } from "monaco-languageclient"
import normalizeUrl from "normalize-url"
import { useEffect, useMemo } from "react"
import { WebSocketMessageReader, WebSocketMessageWriter, toSocket } from "vscode-ws-jsonrpc"

export type MonacoEditorPropsType = {
	path: string
	code: string
	setCode: (newCode: string) => void
	editorOptions: any
}

export function createUrl(hostname: string, port: string, path: string): string {
	const protocol = location.protocol === "https:" ? "wss" : "ws"
	return normalizeUrl(`${protocol}://${hostname}:${port}${path}`)
}

function createLanguageClient(transports: any) {
	return new MonacoLanguageClient({
		name: "Sample Language Client",
		clientOptions: {
			// use a language id as a document selector
			documentSelector: ["java"],
			// disable the default error handler
			errorHandler: {
				error: () => ({ action: ErrorAction.Continue }),
				closed: () => ({ action: CloseAction.DoNotRestart }),
			},
		},
		// create a language client connection from the JSON RPC connection on demand
		connectionProvider: {
			get: () => {
				return Promise.resolve(transports)
			},
		},
	})
}

function createWebSocket(url: string) {
	const webSocket = new WebSocket(url)
	webSocket.onopen = () => {
		const socket = toSocket(webSocket)
		const reader = new WebSocketMessageReader(socket)
		const writer = new WebSocketMessageWriter(socket)
		const languageClient = createLanguageClient({
			reader,
			writer,
		})
		languageClient.start()
		reader.onClose(() => languageClient.stop())
	}
}

const MonacoEditorWrapper = (props: MonacoEditorPropsType): JSX.Element => {
	const { path, code, setCode, editorOptions } = props

	const getLatestCode = (code: string) => {
		return typeof code === "string" ? JSON.parse(code) : code
	}

	const hostname = "localhost"
	const urlPath = ""
	const port = "4000"
	const url = useMemo(() => createUrl(hostname, port, urlPath), [hostname, port, urlPath])

	useEffect(() => {
		// register Monaco languages
		const monaco = require("monaco-editor/esm/vs/editor/editor.api")
		monaco.languages.register({
			id: "java",
			extensions: [".java"],
			aliases: ["JAVA", "java"],
			mimetypes: ["application/text"],
		})
		// install Monaco language client services
		// MonacoServices.install()
		createWebSocket(url)
	}, [])

	return (
		<Editor
			...editorProps
		/>
	)
}

export default MonacoEditorWrapper

Not knowing where i am missing?

@w3ichen
Copy link
Contributor Author

w3ichen commented Jan 2, 2023

@chaitanya71998 Are you getting this error from loading the monaco editor and not the monaco-languageclient?
I used monac-react and it worked fine: https:/suren-atoyan/monaco-react

@chaitanya71998
Copy link

I am getting it after importing monaco-languageclient in editor file i shared above. Did the above steps worked for you with monaco react?

@kaisalmen
Copy link
Collaborator

Hi @chaitanya71998 I am not familiar with Next.js, but these issues seem to be related to general code assembly/bundling especially inconsistent configuration regarding commonjs/esm modules.

Have you checked our troubleshooting section? https:/TypeFox/monaco-languageclient#troubleshooting This should help you avoid some common pitfalls.

With regard to our react our example is just that an example. https:/suren-atoyan/monaco-react can be used with monaco-languageclient it is also mentioned in the Troubleshooting section.

@w3ichen
Copy link
Contributor Author

w3ichen commented Jan 3, 2023

// next.config.js
//@ts-nocheck
const withTM = require("next-transpile-modules")([
	// `monaco-editor` isn't published to npm correctly: it includes both CSS
	// imports and non-Node friendly syntax, so it needs to be compiled.
	"monaco-editor",
])
module.exports = withTM({
	reactStrictMode: true,
	swcMinify: true,
	webpack: webpackConfig => {
		// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
		webpackConfig.experiments.topLevelAwait = true
		// eslint-disable-next-line @typescript-eslint/no-unsafe-return
		return webpackConfig
	},
	eslint: {
		// Warning: This allows production builds to successfully complete even if
		// your project has ESLint errors.
		ignoreDuringBuilds: true,
	},
})

@chaitanya71998 I tried with the "next-transpile-modules" of ["monaco-editor"], but it didn't work for me.
I got it to work instead by:

  1. Removing appDir - best not to use appDir as it is still an experimental feature
  2. "next-transpile-modules" of monaco-languageclient - monaco-editor was not the issue, it was monaco-languageclient

So next.config.js looks like this:

const withTM = require("next-transpile-modules")(["monaco-languageclient"])
module.exports = withTM({ })

In NextJS 13, next-transpile-modules is built-in as transpilePackages

module.exports = {
  transpilePackages: ["monaco-languageclient"], 
};

@w3ichen w3ichen closed this as completed Jan 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants