Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js SyntaxError "Unexpected token 'export'"

Tags:

next.js

I'm trying to import a functions from a dependency to my next/react functional component, but somehow I keep getting the following error:

SyntaxError: Unexpected token 'export'

That's the function I'm trying to import:

export function classes(...args) {
    const list = [];
    for (let i = 0; i < args.length; i++) {
        const entry = args[i];
        if (typeof entry === "string") {
            list.push(entry);
        }
        else {
            for (let key in entry) {
                if (entry[key]) {
                    list.push(key);
                }
            }
        }
    }
    return list.join(" ");

There additionally is a classes.d.ts next to the classes.js above:

export declare function classes(...args: Array<string | {
    [key: string]: any;
}>): string;

Exporting this code identically from within the project works fine, but not when I use an external library from node_modules. How so?

Read about next-transpile-module, but haven't been able to make it run with this one either.

The only way to make the import work is using relative paths ../../node_modules/thedependency/class - how can I make it work properly?

like image 806
Tim Avatar asked Jan 28 '21 11:01

Tim


2 Answers

So the dependency in node_modules folder exports a function using ES6 import/export module. The code will throw error when it running in browser since browser cannot recognize the ES6 module syntax.

The reason is that, by default, Next.js configs the babel-loader to only transpile the ES6 code in the src folder, any ES6 code imported from node_modules will directly go into final bundle without transpiling.

Try to modify the webpack config in next.config.js file to let the babel loader transpile the es6 dependency. You may want to use this package next-transpile-modules

like image 192
MarkoCen Avatar answered Nov 11 '22 13:11

MarkoCen


There's another way:

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('package'),
  { ssr: false }
)

// ...


// use it in render like:
<DynamicComponentWithNoSSR />

Found in https://stackoverflow.com/a/60738624/3051080

Context:

I was getting the same error: Unexpected token 'export'; with a node_modules dependency made for the browser (client-side). I tried with @MarkoCen's answer with no luck, because I got a window is not defined error later.

The dynamic approach did the trick.

like image 4
Gus Avatar answered Nov 11 '22 12:11

Gus