1

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

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

===代码库中的一些文件===

我的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 问题。请给我一些方向,看看哪里。

4

1 回答 1

1

错误在于我如何尝试构建我的库。libraryTarget 未在webpack.config.js. 原来的配置是

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 文档

libraryTarget: 'umd' - 这会在所有模块定义下公开你的库,允许它与 CommonJS、AMD 和作为全局变量一起使用。

由于这是我最初的要求,我的库应该可以通过浏览器es6 import或作为script浏览器中的标签使用。

于 2019-04-22T07:25:08.293 回答