【发布时间】:2018-06-13 01:11:23
【问题描述】:
我正在使用 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;
`
从 documentation example 看来 - 我应该得到类似 ... <button class="Button-asdf123 asdf123" /> instead of just <button class="asdf123" />. 但我没有。
深入研究后,我发现了这个issue (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 是否在所有地方都被使用?
P.S. 在我的情况下,我在客户端获得的那些类有这个前缀 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
}
}
【问题讨论】:
标签: javascript reactjs babeljs styled-components nextjs