我有一个样式化组件,希望将其打包成NPM包并能够在其他项目中导入。
我的样式化组件大致如下:
// src/StyledDiv.styles.js
import styled from "styled-components"
const StyledDiv = styled("div")`
border: solid red 1px;
border-radius: 5px;
padding: 20px;
margin: 15px;
`
export default StyledDiv
我有一个构建脚本,可以将代码转换为 dist 文件夹:
"build": "babel src -d dist --copy-files --ignore './src/**/*.test.js'",
// .babelrc
{
"presets": ["env", "react"]
}
我在我的样式化组件项目中运行
npm link
,然后在我的另一个项目中运行npm link <styled component>
来尝试导入它,但是似乎出现了错误: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
我认为这是由于babel没有正确转换我的样式化组件,因此当我导入dist中的构建文件时,应用程序会崩溃。我的完整package.json如下:{
"name": "my-styled-component",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "jest ./src/**/*.test.js --notify --detectOpenHandles",
"test:watch": "jest ./src/**/*.test.js --notify --watch",
"start": "webpack-dev-server --mode development",
"build": "babel src -d dist --copy-files --ignore './src/**/*.test.js'",
"lint:css": "stylelint './src/**/*.styles.js'"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-jest": "^24.8.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^2.1.1",
"html-webpack-plugin": "^3.2.0",
"jest": "^24.8.0",
"jest-styled-components": "^6.3.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.8.6",
"style-loader": "^0.23.1",
"stylelint": "^10.0.1",
"stylelint-config-recommended": "^2.2.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.6.0",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1",
"webpack-dev-server": "^3.3.1"
},
"dependencies": {
"styled-components": "^4.2.0",
"styled-tools": "^1.7.1"
}
}