我的最终目标是建立一个npm软件包的功能库。我遇到错误“ x不是函数”。因此,我整理了一个基本示例,如下所示。
package.json
{
"name": "@klequis/npm-step-by-step",
"version": "0.0.1",
"description": "learning npm-packaging step by step",
"main": "index.js",
"scripts": {
"build": "babel src --out-dir lib"
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.3",
"@babel/preset-env": "^7.3.1"
}
}
babel.config.js
const presets = [
[
"@babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
useBuiltIns: "usage",
},
],
];
module.exports = { presets };
src / add.js
const add = (a, b) => {
return a + b
}
export default add
lib / add.js-运行构建后的结果
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const add = (a, b) => {
return a + b;
};
var _default = add;
exports.default = _default;
test.js
var add = require('./lib/add')
console.log(add(1,3))
在test.js中,VS Code在消息中立即在“ add”下划线:无法调用类型缺少调用签名的表达式。类型'importof type(“ / home / me / dev / learn / npm-packaging / step-by-step / lib / add”)没有兼容的呼叫签名。
在Commandlien上使用节点运行
$ node test.js
结果
/home/me/dev/learn/npm-packaging/step-by-step/test.js:3
console.log(add(1,3))
^
TypeError: add is not a function
at Object.<anonymous> (/home/me/dev/learn/npm-packaging/step-by-step/test.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)