尽管peerDependency存在于node_modules中,但尚未定义

时间:2019-04-18 10:22:13

标签: javascript npm webpack npm-install npm-publish

我正在学习构建NPM库。可以在HERE中找到其源代码。我将lodash设置为peerDependency,以便应用程序(使用该库)可以自己安装它。

现在的问题是,当我在应用程序中安装库(@a6kme/math)时,导入库时出现错误Unhandled Rejection (ReferenceError): lodash is not defined。我已经检查过,lodash已通过其他一些库由应用程序安装。 (lodash位于node_modules文件夹中)

=== CODE REPOSITORY中的一些文件 ===

我的package.json

{
  "name": "@a6kme/math",
  "version": "1.0.5",
  "description": "",
  "main": "dist/math.js",
  "scripts": {
    "test": "jest",
    "build": "webpack --mode=production",
    "prepare": "npm run test",
    "posttest": "npm run build"
  },
  "files": [
    "/dist"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/a6kme/math.git"
  },
  "keywords": [
    "webpack",
    "webpack-library",
    "bundling",
    "library"
  ],
  "author": "a6kme",
  "license": "MIT",
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "babel-eslint": "^10.0.1",
    "babel-loader": "^8.0.5",
    "eslint": "^5.3.0",
    "eslint-config-prettier": "^4.1.0",
    "eslint-plugin-import": "^2.17.2",
    "eslint-plugin-prettier": "^3.0.1",
    "jest": "^24.7.1",
    "lodash": "^4.17.11",
    "prettier": "1.17.0",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.0"
  },
  "peerDependencies": {
    "lodash": "*"
  }
}

我的webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'math.js',
    library: 'mathJs'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  externals: [/^lodash\/.+$/]
};

我的.babelrc

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

我已经在代码存储库中创建了github issue。 请给我一些方向看。

1 个答案:

答案 0 :(得分:0)

错误与我尝试构建库的方式有关。未在webpack.config.js中设置libraryTarget。最初的配置是

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: 'math.js',
  library: 'mathJs'
}

本来应该是

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: 'math.js',
  library: 'mathJs',
  libraryTarget: 'umd',
  globalObject: 'this'
}

WebPack documents

  

libraryTarget:'umd'-这将在所有模块定义下公开您的库,使其可以与CommonJS,AMD一起使用并作为全局变量使用。

由于这是我的原始要求,因此我的库应该可以通过es6 import或在浏览器中用作script标签来使用。