zmi*_*mii 7 javascript reactjs babeljs styled-components next.js
我正在使用Next.jsReact 应用程序的服务器端渲染(带有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"
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我跑步时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.
Run Code Online (Sandbox Code Playgroud)
但是一旦我进入开发工具并看到一些styled-component我可以看到这一点:class="sc-iyvyFf gGaJAt"但在我的代码中我有这个定义:
const Title = styled.div`
font-size: 40px;
line-height: 1.13;
`
Run Code Online (Sandbox Code Playgroud)
从文档示例看来- 我应该得到类似的东西... <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有效或者是否有效,但我没有在样式组件的声明中设置任何特殊属性,因此得到这个通用前缀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
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,之前似乎没有人回答过这个问题;
您所看到的可能归结为您发布的这一小段代码: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”)