【问题标题】:Publish a npm package that is built using webpack and babeljs发布使用 webpack 和 babeljs 构建的 npm 包
【发布时间】:2019-06-07 12:27:32
【问题描述】:

我构建了一个非常简单的 javascript,它使用 webpack 进行打包,使用 npm 发布项目。虽然我能够成功构建和发布项目,但我无法使用导出的功能。

这是我的 package.json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/test-prod.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --display-error-details --mode production",
    "prepublishOnly": "npm run build"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.28.4",
    "webpack-cli": "^3.2.1"
  }
}

这里是 webpack 配置:

const path = require('path');

module.exports = {
    context: path.resolve(__dirname),
    entry: './index.js', // Entry file that will be invoked by webpack first
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'test-prod.js'
    }
};

这是我打算导出的“src”文件夹中的测试函数:

export const testFunc = () => alert('Hello World!');

这里是 index.js:

const testFunc = require("./src/testFunc");

module.exports = {testFunc};

这一切都很好。但是在执行npm publishnpm link 之后,我无法从另一个项目访问testFunc。

我尝试了import * as functions from 'test';,然后是functions.testFunc()import {testFunc} from 'test';。两者都不起作用。

请告诉我如何使用 webpack 和 npm 正确导出函数,并从不同的项目中访问它。我只需要已发布包中的缩小 javascript。

【问题讨论】:

  • 由于某种原因,我无法编辑自己的问题。我根本没有使用 babel。它只是 webpack,javascript,。和 npm。
  • 看看我可能会尝试const { testFunc } = require("./src/testFunc"); module.exports = testFunc
  • 我进行了更改,执行了 npm 链接并尝试从另一个项目访问它。还是不行。
  • 你能显示终端错误吗?
  • 这是我在另一个项目import {testFunc} from 'test'; 中导入的方式。当我尝试调用函数 testFunc(); 时,出现以下错误:'TypeError: Object(...) is not a function'。另一个项目是一个反应网络应用程序,所以这是我从浏览器得到的错误。

标签: javascript npm webpack


【解决方案1】:

试试这个。

在 webpack 配置文件中,添加这个

    output: {
        // your current code
        library: 'test',
        libraryTarget: 'umd'
    }

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 2016-05-09
    • 2018-04-24
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2020-12-23
    相关资源
    最近更新 更多