使用我在 Gatsby 网站上使用 Babel 和 Rollup 创建的 ES6 React Lib

我创建了一个简单的 React Lib,用于componentDidMount将外部脚本注入 dom,如下所示:


import { Component } from "react"


class Embed extends Component {

  componentDidMount () {

    const script = document.createElement("script")

    script.async = true

    script.src = "https://cdn.mysite.com/embed.js"

    document.head.appendChild(script);

  }


  render() {

    return null

  }

}


export default Embed

这个文件在src/components/Embed.js


然后在src/index.js我有:


import Embed from './components/Embed'

export default Embed

我的package.json样子是这样的:


{

  "name": "my-embed-js",

  "version": "1.3.0",

  "description": "A react wrapper for my embed script",

  "main": "dist/index.cjs.js",

  "module": "dist/index.esm.js",

  "browser": "dist/index.js",

  "files": [

    "dist"

  ],

  "scripts": {

    "build": "rollup -c",

    "dev": "rollup -c -w",

    "test": "echo \"Error: no test specified\" && exit 1",

    "prepublish": "rm -rf ./dist && npm run build"

  },


  "keywords": [],

  "author": "Me",

  "license": "MIT",

  "devDependencies": {

    "@babel/core": "^7.9.0",

    "@babel/preset-env": "^7.9.0",

    "@babel/preset-react": "^7.9.0",

    "@rollup/plugin-commonjs": "^11.0.2",

    "@rollup/plugin-node-resolve": "^7.1.1",

    "react": "^16.13.1",

    "react-dom": "^16.13.1",

    "rollup": "^2.3.2",

    "rollup-plugin-babel": "^4.4.0",

    "rollup-plugin-peer-deps-external": "^2.2.2"

  },

  "peerDependencies": {

    "react": "^16.13.1",

    "react-dom": "^16.13.1"

  }

}

我.babelrc的很简单:


{

  "presets": [

    "@babel/env",

    "@babel/react"

  ]

}

在我的rollup.config.js文件中:


import peerDepsExternal from 'rollup-plugin-peer-deps-external'

import babel from 'rollup-plugin-babel'

import resolve from '@rollup/plugin-node-resolve'

import commonjs from '@rollup/plugin-commonjs'

import pkg from './package.json'


const INPUT_FILE_PATH = 'src/index.js';

const OUTPUT_NAME = 'MyEmbedJs';


这里发生了什么?除了我只是把我带入死胡同的 linter 东西之外,我没有看到任何有用的错误消息。有什么想法吗?


胡子哥哥
浏览 126回答 1
1回答

繁星淼淼

我能够通过删除我的库的 UMD 部分来修复错误:从rollup.config.js删除:  {    file: pkg.browser,    format: 'umd',  },并从package.json删除:"browser": "dist/index.js",
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript