6

我正在Next.js用于 React 应用程序的服务器端渲染(带有styled-components),并且我使用 Babel 插件来显示我在代码中使用的组件的名称存在问题。

这是我的.babelrc文件:

{
  "env": {
    "development": {
      "presets": ["next/babel"],
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "ssr": true,
            "displayName": true,
            "preprocess": false
          }
        ]
      ]
    },
    "production": {
      "presets": "next/babel",
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "displayName": false,
            "ssr": true
          }
        ]
      ]
    },
    "test": {
      "presets": [
        [
          "env",
          {
            "modules": "commonjs"
          }
        ],
        "next/babel"
      ]
    }
  }
}

当我跑步时cross-env NODE_ENV=development concurrently "tsc --watch" next

我得到了这些行-.babelrc在编译期间使用了含义:

[1] > Using external babel configuration
[1] > Location: "...../.babelrc"
[1] > Using "webpack" config function defined in next.config.js.

但是一旦我去开发工具并看到一些styled-component我可以看到这个:class="sc-iyvyFf gGaJAt"但是在我的代码中我有这个定义:

const Title = styled.div`
  font-size: 40px;
  line-height: 1.13;
`

文档示例中可以看出 - 我应该得到类似... <button class="Button-asdf123 asdf123" /> instead of just <button class="asdf123" />.但我没有。

深入研究后,我发现了这个问题https://github.com/styled-components/styled-components/issues/1103#issuecomment-324302997),基于我在浏览器控制台中遇到的错误:

It seems that only the server code is being transpiled and not the client code

所以问题:如何测试 babel 是否正常工作并.babelrc在所有地方都被使用?

PS在我的情况下,我在客户端获得的那些类sc-在我的脑海中具有这个前缀含义styled-components。所以我不确定插件是否.babelrc完全有效,但我没有在 styled-components 的声明中设置任何特殊属性,因此得到了这个通用前缀sc-

更新这是我正在使用的自定义 next.conf.js

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const { ANALYZE } = process.env
const path = require('path')

module.exports = {
  exportPathMap: function() {
    return {
      '/': { page: '/' }
    }
  },
  webpack: function(config) {
    if (ANALYZE) {
      config.plugins.push(
        new BundleAnalyzerPlugin({
          analyzerMode: 'server',
          analyzerPort: 8888,
          openAnalyzer: true
        })
      )
    }

    config.resolve.alias = {
      'styled-components': path.resolve('./node_modules/styled-components/')
    }

    return config
  }
}
4

1 回答 1

2

不幸的是,以前好像没有人回答过这个问题;

您所看到的可能归结为您发布的一小段代码:tsc --watch

如果您在 Babel 之前执行 TypeScript 转译并将其留给 TypeScript 转译为 ES5,它将转译所有标记的模板文字,而不会给我们的插件任何挂钩。

由于您已经在使用 next.js,因此您无需从头开始设置 Babel 管道。相反,您只需要在 TypeScript 中禁用这种类型的转译。

我建议你设置target在你的tsconfig.jsonto里面,ESNext这样它就可以把一切都交给 Babel 了。

https://www.typescriptlang.org/docs/handbook/compiler-options.html(见“--target”)

于 2018-02-14T00:42:12.350 回答