发布使用webpack和babeljs构建的npm软件包

时间:2019-01-13 03:38:40

标签: javascript npm webpack

我构建了一个非常简单的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。

1 个答案:

答案 0 :(得分:0)

尝试一下。

在webpack配置文件中,添加此

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