I'm struggling to set up my emacs web-mode for .js files for React projects. They don't get indented properly. A known fix is to force the .js files into .jsx files, however, I'm not able to get that to work either (check this other question)
When I open up an emacs window that's .js, web-mode & prettier are set up correctly BUT if I eval web-mode-content-type -> "javascript" instead of "jsx".
I tried a few changes and drilled it down to the point where I found out the variable: web-mode-content-type is not defined while .emacs gets executed so the if returns false. I however, have no idea how to fix this.
Full ~/.emacs here:
(message "Loading init.el")
;; Adding MELPA
(require 'package)
(add-to-list 'package-archives
'("melpa" . "https://melpa.org/packages/") t)
;; Dark theme mode
(load-theme 'modus-vivendi t)
;; Use HELM instead of default
(global-set-key (kbd "M-x") 'helm-M-x)
(global-set-key (kbd "C-x C-f") 'helm-find-files)
(global-set-key (kbd "C-x b") 'helm-buffers-list)
;; Expressing that I don't want to see the startup by emacs
(require 'web-mode)
(add-to-list 'auto-mode-alist '("\\.js\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.jsx\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.ts\\'" . web-mode))
(add-to-list 'auto-mode-alist '("\\.tsx\\'" . web-mode))
(add-hook 'web-mode-hook
(lambda ()
(if (equal web-mode-content-type "javascript")
(web-mode-set-content-type "jsx")
(message "now set to: %s" web-mode-content-type)
)
)
)
(add-hook 'web-mode-hook 'prettier-js-mode)
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(inhibit-startup-screen t)
'(package-selected-packages '(prettier-js web-mode helm modus-themes)))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
web-mode, but: don't putlambdaexpressions in hook variables -- especially if you're experimenting with variations, you're liable to wind up with multiple different versions in the same hook, all running and stepping on each other's toes. Define a named function and add that symbol to the hook, and then you can tweak the function definition without doing bad things to the hook.web-mode-content-types-alist, eg.(setq web-mode-content-types-alist '(("jsx" . "\\.js[x]?\\'")))as shown in its docstring. FYI, there are modes that work well with React you may want to consider: the builtin modesjs-jsx-mode,tsx-ts-mode,js-ts-mode, and external packagerjsx-mode.