【问题标题】:Creating own node modules to export and import via babel transpiler创建自己的节点模块以通过 babel transpiler 导出和导入
【发布时间】:2021-12-01 17:35:41
【问题描述】:

我的目标是在另一个项目中做这样的事情

import { FuncA, FuncB, FuncC } from @myorg/hellow

我正在为内部问题创建自己的节点模块,并且我已经定义了hello的文件夹结构如下:

????hellow
 ┣ ????dist(ES5 of src)
 ┣ ????src
 ┃ ┣ ????Fileone
 ┃ ┃ ┗ ????Fileone.js
 ┃ ┃ ????Filetwo
 ┃ ┃ ┗ ????Filetwo.js
 ┃ ┗ ????index.js
 ┣ ????.babelrc
 ┣ ????.gitignore
 ┣ ????.npmignore
 ┣ ????index.js
 ┣ ????package-lock.json
 ┗ ????package.json

index.js 看起来像这样:

module.exports = require('./dist');

省略了一些字段的 package.json 如下所示:

"main": "index.js",
    "scripts": {
        "build": "npx babel src --out-dir dist"
    },
    "license": "MIT",
    "devDependencies": {
        "@babel/cli": "^7.16.0",
        "@babel/core": "^7.16.0",
        "@babel/preset-env": "^7.16.4",
        "@babel/preset-react": "^7.12.13",
        "create-index": "^2.6.0"
    },

.babelrc 文件如下所示:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

src 文件夹中的 index.js 充当 Fileone.js、Filetwo.js 中导出函数的聚合器,因此它看起来像这样:

export { FuncA, FuncB } from './Fileone/Fileone.js';
export { FuncC } from './Filetwo/Filetwo.js';

然后文件 Fileone.js(和类似的 Filetwo.js)有一些类似的代码:

const FuncA = ...
const FuncB = ...
...
export { FuncA, FuncB }

像这样设置包后,我执行以下操作以发布到 npm

npm run build
npm publish
cd ../project-directory
npm update @myorg/hellow
npm run dev

我得到的错误与缺少语法有关:

“错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:未定义。您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认导入和命名导入。”

.next\server\pages\_document.js (12:4) @ Object.ctx.renderPage

  10 |          // eslint-disable-next-line no-param-reassign
  11 |          ctx.renderPage = () =>
> 12 |              originalRenderPage({
     |          ^
  13 |                  enhanceApp: App => props =>
  14 |                      sheet.collectStyles(<App {...props} />),
  15 |              });

但是我浏览了很多,无法弄清楚我哪里出错了。我猜这与转译成 ES5 有关系?


编辑:我已经删除了 root index.js 文件并修改了 package.json 使得条目如下所示:

~~"main": "index.js"~~
"main": "dist/index.js"

同样的错误。

【问题讨论】:

    标签: javascript node.js reactjs npm


    【解决方案1】:

    原来在我上面提到的步骤中:


    src 文件夹中的 index.js 充当 Fileone.js、Filetwo.js 中导出函数的聚合器,因此它看起来像这样:

    export { FuncA, FuncB } from './Fileone/Fileone.js';
    export { FuncC } from './Filetwo/Filetwo.js';
    

    我需要改用:

    export { FuncA, FuncB } from './Fileone/Fileone';
    export { FuncC } from './Filetwo/Filetwo';
    

    没有 .js 扩展名。似乎现在可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-21
      • 2015-09-13
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 2021-08-15
      相关资源
      最近更新 更多