如何在使用NextJS时配置“babel-plugin-styled-components”?

8ulbf1ek  于 2023-06-22  发布在  Babel
关注(0)|答案(1)|浏览(228)

我在用

"next": "12",
"babel-plugin-styled-components": "^1.13.2",

一个typescript nextjs项目。样式化的组件工作得很好,但现在我想隐藏它们的显示名称。
出于这个原因,我添加了额外的配置到我已经存在的babel.config.js

module.exports = function (api) {
    return {
        presets: presets,
        plugins: [
            [
                'styled-components',
                {
                    ssr: true,
                },
            ],
            // below is the new part i added to already working babel config    
            [
                'babel-plugin-styled-components',
                {
                    namespace: 'my-styled-components-project',
                    displayName: false,
                    fileName: false,
                },
            ],
        ],
    };
};

添加'babel-plugin-styled-components',部分后,下一个开发失败

error - ./node_modules/next/dist/client/dev/amp-dev.js
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.

  plugins: [
    ['some-plugin', {}],
    ['some-plugin', {}, 'some unique name'],
  ]

Duplicates detected are:
[
  {
    "alias": "/usr/src/app/node_modules/babel-plugin-styled-components/lib/index.js",
    "options": {
      "ssr": true
    },
    "dirname": "/usr/src/app",
    "ownPass": false,
    "file": {
      "request": "styled-components",
      "resolved": "/usr/src/app/node_modules/babel-plugin-styled-components/lib/index.js"
    }
  },
  {
    "alias": "/usr/src/app/node_modules/babel-plugin-styled-components/lib/index.js",
    "options": {
      "namespace": "my-styled-components-project",
      "displayName": false,
      "fileName": false
    },
    "dirname": "/usr/src/app",
    "ownPass": false,
    "file": {
      "request": "babel-plugin-styled-components",
      "resolved": "/usr/src/app/node_modules/babel-plugin-styled-components/lib/index.js"
    }
  }
]
    at createDescriptors.next (<anonymous>)
    at createPluginDescriptors.next (<anonymous>)
    at plugins.next (<anonymous>)
    at mergeChainOpts.next (<anonymous>)
7z5jn7bk

7z5jn7bk1#

我找到了解决方案,因为接下来是替换配置的名称空间必须只使用styled-components
这里令人困惑的是,babel-plugin-styled-components的官方文档显示了使用该名称空间的babel.config.js示例
所以下面的工作正常

module.exports = function (api) {
    return {
        presets: presets,
        plugins: [
            [
                'styled-components',
                {
                    ssr: true,
                    namespace: 'my-styled-components-project',
                    displayName: false,
                    fileName: false,
                },
            ],
        ],
    };
};

相关问题