【问题标题】:i create my own npm package and publish it but when i trying to use it, it gives me an error我创建自己的 npm 包并发布它,但是当我尝试使用它时,它给了我一个错误
【发布时间】:2018-04-16 17:19:55
【问题描述】:

我创建 reactjs 组件并使其在 npm 上发布。我将它安装在我的另一个项目中,现在当我尝试导入它时给出完整路径,例如

import RippleIcon from '../node_modules/rippleicon/src/RippleIcon';

它给了我一个错误

./node_modules/rippleicon/src/RippleIcon.js
Module parse failed: Unexpected token (10:8)
You may need an appropriate loader to handle this file type.
|   render() {
|     return (
|         <i className={this.props.icon+" RippleIcon"}/>
|     );
|   }

rippleicon 是我的 npm 包名称,我在 create-react-app 上创建我的包。欢迎任何建议。谢谢。

这是我的 package.json

{
 "name": "packagetesting",
 "version": "0.1.0",
 "private": true,
 "dependencies": {
   "react": "^16.3.2",
   "react-dom": "^16.3.2",
   "react-scripts": "1.1.4",
   "rippleicon": "^0.1.1"
},
"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}
}

【问题讨论】:

    标签: reactjs npm package npm-install


    【解决方案1】:

    创建节点包并将其链接到项目相对容易。假设您将有 mypackagemyproject 在同一路径上,请尝试以下步骤:

    1.- 包

    $ mkdir mypackage
    $ cd mypackage/
    $ npm init -y
    $ echo "exports.myfunc = function() { console.log(\"Hello\"); }" > index.js
    $ cd ..
    

    它的package.json 内容将是:

    {
      "name": "mypackage",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }
    

    2.- 项目

    $ mkdir myproject
    $ cd myproject/
    $ npm init -y
    $ npm install "file:../mypackage" --save
    $ echo "var mp = require('mypackage'); mp.myfunc();" > index.js
    $ node index.js
    

    您会看到打印了“Hello”。它的package.json 内容将是:

    {
      "name": "myproject",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "mypackage": "file:../mypackage"
      }
    }
    

    【讨论】:

    • 是的,有一些:1- "rippleicon": "file:local/path/to/package", 2- "main": "src/index.js", 3- import RippleIcon来自'ripleicon'等。我不知道你的项目细节,但你可以找出不正确的地方。
    • 好吧,我做了一个反应组件,然后 npm run build 并将其发布到 npm 包,现在我创建另一个项目并通过 npm 安装该包。所以当我导入它时,它给了我一个错误,你可能需要一个合适的加载器来处理这种类型的文件。
    • 我明白,但是您在配置和导入本地包时出错。
    • 我必须从完整路径导入它,否则它会给我模块找不到错误。我用谷歌搜索,但他们提到了 webpack 文件,我不知道它的用途。
    • 你可以在 Github.com/amitruls1/rippleicon.git 上查看我的代码
    猜你喜欢
    • 2023-04-06
    • 2022-01-14
    • 2022-12-17
    • 1970-01-01
    • 2020-02-28
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多