Я пытаюсь обойти эту ошибку, и моя пользовательская конфигурация babel успешно выполнила сборку.Я также анализирую пакет, используя next-bundle-analyzer
. Babel требует, чтобы api.cache () вызывался в babel.config.js для документов ивыдает ошибку, если не вызывается.
Мой стек: Firebase, Next.js, React, Node
Next.js использует свою конфигурацию babel по умолчанию при сборке, если она не найдена в корневом каталоге, где вызывается next build
.
Мой проект является моно-репо из-за необходимости (потому что интеграция Next.js / Firebase) и примерно так:
myProject
│
└───src
│ │
│ └───app
│ │ │
│ │ └───components
│ │ │
│ │ └───pages
│ │ │
│ │ │ babel.config.js
│ │ │ next.config.js
│ │ │ package.json
│ │
│ │
│ └───functions
│ │ │
│ │ └───next
│ │ │
│ │ │ package.json
│
│
package.json
Вот мой babel.config.js
module.exports = function babelConfig(api) {
api.cache(true);
const presets = [
"@babel/preset-flow",
[
"next/babel",
{
"preset-env": {
"useBuiltIns": "usage"
}
}
]
];
const plugins = [
"@babel/plugin-transform-modules-commonjs",
"transform-semantic-ui-react-imports",
"@babel/plugin-transform-flow-strip-types",
"@babel/plugin-syntax-dynamic-import",
[
"module-resolver",
{
"root": ["."],
"alias": {
"styles": "scss/"
},
"cwd": "babelrc"
}
],
[
"wrap-in-js",
{
"extensions": ["css$", "scss$"]
}
],
"styled-jsx/babel",
"@babel/plugin-transform-regenerator",
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
];
return {
presets,
plugins
};
}
Вот мой next.config.js
const withOptimizedImages = require('next-optimized-images');
const withCSS = require('@zeit/next-css');
const withBundleAnalyzer = require('@zeit/next-bundle-analyzer');
module.exports = (nextConfig = {}) =>
Object.assign(
{},
nextConfig,
withBundleAnalyzer(
withOptimizedImages(
withCSS({
distDir: '../functions/next',
webpack: (config, options) => {
config.module.rules.push(
{
test: /\.(jpe?g|png|gif|svg|eot|ttf)$/i,
loader: ['url-loader?limit=10000', 'img-loader'],
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/fontwoff',
},
);
config.node = {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty',
};
// Important: return the modified config
return config;
},
analyzeServer: ["server", "both"].includes(process.env.BUNDLE_ANALYZE),
analyzeBrowser: ["browser", "both"].includes(process.env.BUNDLE_ANALYZE),
bundleAnalyzerConfig: {
server: {
analyzerMode: 'static',
generateStatsFile: true,
reportFilename: './server.html',
},
browser: {
analyzerMode: 'static',
generateStatsFile: true,
reportFilename: './client.html'
}
},
})
)
),
);
это скрипт сборки, расположенный в корне проекта:
"build-next": "cd \"src/functions\" && rm -rf next && cd \"../app\" && rm -rf node_modules/.cache && yarn && BUNDLE_ANALYZE=browser yarn build",
приведенный выше скрипт вызывает ниже *Сценарий 1026 *, определенный в /src/app/package.json
"build": "next build",
Когда я запускаю yarn build-next
в корне проекта, в консоли появляется сообщение об ошибке:
$ yarn build-next
yarn run v1.3.2
$ cd "src/functions" && rm -rf next && cd "../app" && rm -rf node_modules/.cache && yarn && BUNDLE_ANALYZE=browser yarn build
[1/4] ? Resolving packages...
success Already up-to-date.
$ next build
Creating an optimized production build ...
> Using external babel configuration
> Location: "myProject/src/app/babel.config.js"
Failed to compile.
./pages/category1/subCategory1/my-page.js
TypeError: Cannot read property 'cache' of undefined
> Build error occurred
Error: > Build failed because of webpack errors
at Object.build [as default] (myProject/src/app/node_modules/next/dist/build/index.js:192:15)
at <anonymous>
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Я пытался выброситьconsole.log('api: ', api)
в babel.config.js
, чтобы увидеть, что происходит с параметром api
, который не определен.Странно, но сначала он регистрируется в консоли, затем кажется, что конфигурация babel выполняется несколько раз, а api
не определяется при последующих выполнениях.
Вот вывод console.log в верхней части babel.config.js:
$ yarn build-next
yarn run v1.3.2
$ cd "src/functions" && rm -rf next && cd "../app" && rm -rf node_modules/.cache && yarn && BUNDLE_ANALYZE=browser yarn build
[1/4] ? Resolving packages...
success Already up-to-date.
$ next build
Creating an optimized production build ...
api: { version: '7.1.2',
cache:
{ [Function: cacheFn]
forever: [Function],
never: [Function],
using: [Function],
invalidate: [Function] },
env: [Function: env],
async: [Function: async],
caller: [Function: caller],
assertVersion: [Function: assertVersion] }
> Using external babel configuration
> Location: "/myProject/src/app/babel.config.js"
api: undefined
api: undefined
api: undefined
api: undefined
[DELETED - repeated many times]
api: undefined
Failed to compile.
./pages/category1/subCategory1/my-page.js
TypeError: Cannot read property 'cache' of undefined
> Build error occurred
Error: > Build failed because of webpack errors
at Object.build [as default] (myProject/src/app/node_modules/next/dist/build/index.js:192:15)
at <anonymous>
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Update:
Я пытался обновиться до последней @babel/core
, но ничего не сделал.Я попытался удалить все плагины, и сборка завершена успешно.Проблема связана с одним или несколькими плагинами.Я добавляю обратно один плагин за раз, чтобы посмотреть, смогу ли я определить источник.