codemirror / codemirror5

In-browser code editor (version 5, legacy)
http://codemirror.net/5/
MIT License
26.79k stars 4.96k forks source link

Loading CodeMirror with webpack (solved) #5484

Closed correnson closed 6 years ago

correnson commented 6 years ago

Hi all,

I report here an issue that is somehow related to #4838 and to other similar open questions on various forums. I found the problem when using webpack, but I think the issue also comes when simply using import. There is no « bug » to fix in the code distribution, but I think something could be added in the installation page of the (awesome) CodeMirror manual, which covers many importation schemes but not import explicitly.

Here is the story (with suitable webpack & babel configuration):

  1. Install CodeMirror with yarn add codemirror (or using npm).
  2. Using import CodeMirror from 'codemirror'; works as expected. Good!
  3. Adds import 'codemirror/theme/<myTheme>.css'; for your favorite theme. Very Good!
  4. Adds import 'codemirror/mode/javascript/javascript.js'; seems to Work (no error in console)...
  5. However, selecting the mode does nothing. Worst: CodeMirror.modes reveals to be empty!
  6. Change step 2 with: import CodeMirror from 'codemirror/lib/codemirror.js'; then every thing works magically. Yeah!

Remark: this simple fix in step #6 above also works with electron + webpack + react + react-hot-loader, contrarily with negative comments found here and there on the web.

Explanation: after deep debugging, it appears that when using import CodeMirror from 'codemirror', the adds-on and modes register themselves in an instance of CodeMirror that is different from the imported one.

Actually, all CodeMirror adds-on and modes are using relative paths to their parent '../lib/codemirror.js' module. However, it seems that the module cache (whoever is responsible for it) is confused and does not identify '<cm>' with '<cm>/lib/codemirror.js' even if '<cm>/package.json' properly specifies that the main entry is at ./lib/codemirror.js'.

marijnh commented 6 years ago

it seems that the module cache (whoever is responsible for it)

I think that's Webpack in this case, and I think that should be reported as a bug there. I'm not really interested in adding workarounds for bugs in other tools to CodeMirror's manual (hopefully, they'll go away soon enough).

correnson commented 6 years ago

Fair enough 👍

AdamZaczek commented 5 years ago

Thanks @correnson, works like a charm !

onfuns commented 5 years ago

Thanks,Solved my problem.

truongnmt commented 4 years ago

Working on Rails 6! Thank you 3000!

fabianzwodrei commented 4 years ago

@truongnmt how did you import CodeMirror in Rails6? Did you use webpacker?

bibisixtynine commented 2 years ago

Magic thanks @correnson for sharing how to import CodeMirror ! I was about to get mad !

hrshlmeht commented 1 year ago

Its not allowing me to import from text area and is throwing errors