问题描述
我正在尝试创建样式化的组件库包,以便可以将样式重新用于不同的项目。
- ExampleStyledComponent-我要在其中构建组件的地方。
- Gatsby项目-一个简单的“ Gatsby new”。项目
我设法通过“ npm link”使测试组件正确显示在浏览器中,但是当我应用样式时,在浏览器中不断出现“无效的挂接调用”错误。
软件包-
- src
- TestComponent.js
- index.js
- package.json
TestComponent.js-
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
width: 100%;
background-color: red;
`;
const TestComp = () => {
return (
<Container>
<h1>Hello World</h1>
</Container>
);
};
export default TestComp;
index.js-
import TestComponent from './src/TestComponent';
export default TestComponent;
package.json-
{
"name": "ExampleStyledComponent","version": "1.0.0","description": "","main": "index.js","scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},"keywords": [],"author": "","license": "ISC","peerDependencies": {
"react": "16.x","styled-components": "5.x"
},"dependencies": {},"devDependencies": {
"babel-plugin-styled-components": "^1.11.1","react": "^16.13.1","styled-components": "^5.1.1"
}
}
没有样式组件,此设置可以正常工作。因此,如何在npm-package中使用样式化的组件。我也尝试在我的Gatsby项目中安装依赖项,但是没有运气。
在我的Gatsby项目依赖项中-
"dependencies": {
"babel-plugin-styled-components": "^1.11.1","gatsby": "^2.24.42","gatsby-image": "^2.4.15","gatsby-plugin-manifest": "^2.4.22","gatsby-plugin-offline": "^3.2.23","gatsby-plugin-react-helmet": "^3.3.10","gatsby-plugin-sharp": "^2.6.26","gatsby-plugin-styled-components": "^3.3.10","gatsby-source-filesystem": "^2.3.24","gatsby-transformer-sharp": "^2.5.12","prop-types": "^15.7.2","react": "^16.12.0","react-dom": "^16.12.0","react-helmet": "^6.1.0","styled-components": "^5.1.1"
},
和gatsby-config.js
module.exports = {
siteMetadata : {
title : `Gatsby Default Starter`,description : `Kick off your next,great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,author : `@gatsbyjs`
},plugins : [
`gatsby-plugin-styled-components`,`gatsby-plugin-react-helmet`,{
resolve : `gatsby-source-filesystem`,options : {
name : `images`,path : `${__dirname}/src/images`
}
},`gatsby-transformer-sharp`,`gatsby-plugin-sharp`,{
resolve : `gatsby-plugin-manifest`,options : {
name : `gatsby-starter-default`,short_name : `starter`,start_url : `/`,background_color : `#663399`,theme_color : `#663399`,display : `minimal-ui`,icon : `src/images/gatsby-icon.png`
]
};
我如何将其导入Gatsby index.js页面-
import React from 'react';
import Test from 'examplestyledcomponent';
const IndexPage = () => (
<div>
<Test />
</div>
);
export default IndexPage;
我在浏览器中遇到的错误看起来像这样-
我真的迷失了,所以任何帮助将不胜感激,谢谢!
解决方法
由于SSR的限制,Gatsby需要一个插件来支持样式化组件
他们的文档详细介绍:https://www.gatsbyjs.org/docs/styled-components/
简短版本是将其添加到您的Gatsby网站:
npm i gatsby-plugin-styled-components styled-components babel-plugin-styled-components
然后,在gatsby-config.js
中:
module.exports = {
plugins: [
'gatsby-plugin-styled-components',]
};
应该可以让您正常运行!