Next.js SyntaxError “意外的令牌‘导出’" [英] Next.js SyntaxError "Unexpected token 'export'"
问题描述
我正在尝试将一个函数从依赖项导入到我的下一个/反应功能组件,但不知何故我不断收到以下错误:
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'
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(" ");
上面的classes.js
旁边还有一个classes.d.ts
:
export declare function classes(...args: Array<string | {
[key: string]: any;
}>): string;
从项目中以相同方式导出此代码可以正常工作,但当我使用 node_modules
的外部库时就不行了.怎么样?
Exporting this code identically from within the project works fine, but not when I use an external library from node_modules
. How so?
阅读有关 next-transpile-module
的信息,但也无法使其与这个一起运行.
Read about next-transpile-module
, but haven't been able to make it run with this one either.
使导入工作的唯一方法是使用相对路径 ../../node_modules/thedependency/class
- 我怎样才能使它正常工作?
The only way to make the import work is using relative paths ../../node_modules/thedependency/class
- how can I make it work properly?
推荐答案
所以 node_modules 文件夹中的依赖使用 ES6 导入/导出模块导出一个函数.由于浏览器无法识别 ES6 模块语法,因此代码在浏览器中运行时会抛出错误.
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.
原因是 Next.js 默认配置 babel-loader 只转译 src 文件夹中的 ES6 代码,任何从 node_modules 导入的 ES6 代码将直接进入最终的 bundle 而不转译.
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.
尝试修改 next.config.js
文件中的 webpack 配置,让 babel loader 转译 es6 依赖.你可能想使用这个包 next-transpile-modules
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
这篇关于Next.js SyntaxError “意外的令牌‘导出’"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!