我有一个样式的组件,我想在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
i然后有一个构建脚本,该脚本应将我的代码转移到一个dist文件夹中:
"build": "babel src -d dist --copy-files --ignore './src/**/*.test.js'",
// .babelrc
{
"presets": ["env", "react"]
}
i然后在我的样式组件项目中运行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中导入构建文件时,应用程序崩溃了。
我的完整软件包。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"
}
}
看起来您需要在组件文件中导入反应。
import React from 'react';
您需要在 .babelrc
中使用它:
presets: [
'@babel/env',
'@babel/react',
],