How to properly dynamic import third party lib (e.g. react-ace) in nextjs

Viewed 43

Nextjs newbie here. I need to use the react ace editor in my nextjs project. Due to the nature of nextjs, and react ace needs to use the window object, I have to dynamic import the ace-editor, and it's working fine. However, when I try to use searchbox plugins, an error prompts and says "Reference error: ace is not defined" Error prompts

Here's how I import the modules

import React from 'react';
import dynamic from 'next/dynamic'

const AceEditor = dynamic(() => import('react-ace'), { ssr: false })

const ace = dynamic(() => import('ace-builds/src-noconflict/ace'), { ssr: false })
const acewebpackresolver = dynamic(() => import('ace-builds/webpack-resolver'), { ssr: false })
const modejs = dynamic(import('ace-builds/src-noconflict/mode-javascript'), { ssr: false })
const themetextmate =  dynamic(import('ace-builds/src-noconflict/theme-textmate'), { ssr: false })
const extsearchbox =  dynamic(import('ace-builds/src-noconflict/ext-searchbox'), { ssr: false })

And I've tried the following as well:

import React from 'react';
import dynamic from 'next/dynamic'

const AceEditor = dynamic(() => import('react-ace'), { ssr: false })

dynamic(() => import('ace-builds/src-noconflict/ace'), { ssr: false })
const acewebpackresolver = dynamic(() => import('ace-builds/webpack-resolver'), { ssr: false })
dynamic(import('ace-builds/src-noconflict/mode-javascript'), { ssr: false })
dynamic(import('ace-builds/src-noconflict/theme-textmate'), { ssr: false })
dynamic(import('ace-builds/src-noconflict/ext-searchbox'), { ssr: false })

Here's how I use the Ace-editor

<AceEditor mode="text"
            theme="textmate"
            name={props.file.fileKey}
            height="345px"
            width="100%"
            fontSize={12}
            value={props.file.fileContent}
            onChange={handleValueChange}
            onLoad={editorInstance => {
              editorInstance.container.style.resize = "both";
              // mouseup = css resize end
              document.addEventListener("mouseup", e => (
                editorInstance.resize()
              ));
            }}
            editorProps={{ $blockScrolling: true }}
          />

I think it's due to the fact that ace-builds/src-noconflict/ext-searchbox.js is using the object "ace" at the start, and nextjs dynamic import fails to define the object "ace" globally, so ext-searchbox.js fails.

Please help to clarify if I'm using the import wrong

0 Answers
Related