我正在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
}
}