您答案中的代码是正确的,我希望我能帮助解释原因。我在您的原始代码中看到了两个错误:
1. copy-webpack-plugin配置不正确。
您的原始配置是一个包含一个对象的数组:
new CopyPlugin([
{
from: './node_modules/@pdftron/webviewer/public',
to: './public/webviewer',
},
]),
但为了得到你想要的结果,你需要为插件提供配置object使用键“模式”(包含一个数组),就像您在答案中所做的那样:
new CopyPlugin({
patterns: [
{
from: './node_modules/@pdftron/webviewer/public',
to: './public/webviewer',
},
],
})
您在问题中发布的错误消息解释了插件是如何错误配置的,只是不是以最直观的方式:
ValidationError: Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
- options[0] misses the property 'patterns'. Should be:
[non-empty string | object { from, to?, context?, globOptions?, filter?, toType?, force?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)
2.您的“webpack”方法的返回值不正确。
在最初的代码中,您分配了变量“newconfig”来获取结果config.plugins.push(...)
,然后返回它:
const newconfig = config.plugins.push(
// ... plugin config ...
// Important: return the modified config
return newconfig
但是,正如你可以看到的Array.push 上的 MDN 文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push,Array.push的返回值为数组的长度.
因此,当你写下return newconfig
,这就像写作return config.plugins.length
,当 next.js 期望您返回整个配置对象时。
当您将一个项目推送到数组时,数组会就地修改,因此您不需要捕获新值。因此,您可以简单地返回原始配置:
// Important: return the modified config
return config
您的答案中的代码整体可以正常工作:
const CopyPlugin = require('copy-webpack-plugin')
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
config.plugins.push(
new CopyPlugin({
patterns: [
{
from: './node_modules/@pdftron/webviewer/public',
to: './public/webviewer',
},
],
})
)
// Important: return the modified config
return config
},
}
我不确定为什么您还需要卸载并重新安装copy-webpack-plugin
包裹,除非我缺少什么东西。