簡體   English   中英

發布使用 webpack 和 babeljs 構建的 npm 包

[英]Publish a npm package that is built using webpack and babeljs

我構建了一個非常簡單的 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。

嘗試這個。

在 webpack 配置文件中,添加這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM