如何将样式化的组件转换为NPM包?

时间:2019-05-08 14:40:48

标签: javascript reactjs webpack babel styled-components

我有一个样式化的组件,我想将其内置到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"
  }
}

2 个答案:

答案 0 :(得分:0)

您似乎需要在组件文件中导入react。

import React from 'react';

答案 1 :(得分:0)

您需要在.babelrc中使用它:

    presets: [
      '@babel/env',
      '@babel/react',
    ],