从 npm 包导入 ES6 模块

Import ES6 module from npm package

我创建并发布了我的第一个 npm 包。此包包含 ES6 语法的 JS,并使用 webpack 和 babel 转译为 ES5。

现在我想使用这个 npm 包,但它失败并出现以下错误:

ERROR in ./node_modules/chokidar/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\dev\git\open-source\test\node_modules\chokidar'
 @ ./node_modules/chokidar/index.js 3:9-22
 @ ./node_modules/watchpack/lib/DirectoryWatcher.js
 @ ./node_modules/watchpack/lib/watcherManager.js
 @ ./node_modules/watchpack/lib/watchpack.js
 @ (webpack)/lib/node/NodeWatchFileSystem.js
 @ (webpack)/lib/node/NodeEnvironmentPlugin.js
 @ (webpack)/lib/webpack.js
 @ ./node_modules/technology-radar/webpack.config.js
 @ ./sample/app.js

为了便于使用,我有以下(最少的)文件集

package.json:

"devDependencies": {
  "babel-cli": "^6.26.0",
  "babel-core": "^6.26.0",
  "babel-loader": "^7.1.2",
  "babel-preset-env": "^1.6.0",
  "babel-preset-es2015": "^6.24.1",
  "webpack": "^3.5.6",
  "webpack-dev-server": "^2.4.5",
  "babel-polyfill": "^6.26.0",
  "html-webpack-plugin": "^2.28.0"
},
"dependencies": {
  "d3": "3.5.17",
  "technology-radar": "^1.0.3"
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')

module.exports = {
    entry: {
        sample: './sample/app.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                include: [
                    path.resolve(__dirname, "sample")
                ],
                test: /\.js$/
            }
        ]
    },
    plugins: [
        new UglifyJSPlugin(),
        new HtmlWebpackPlugin({
            template: 'sample/index.html',
            filename: 'index.html',
            inject: 'body'
        })
    ],
    devtool: "#source-map"
};

sample/app.js

import Radar from 'technology-radar';

var radar = new Radar("#techradarContainer");
radar.render();

不知道用法上有没有,npm包本身有没有。 软件包的源代码可在 github at https://github.com/raman-nbg/techradar. The npm package is available at https://www.npmjs.com/package/technology-radar.

上获得

应该导出的 class(定义为包 webpack.config.js 中的入口点)被定义为 src/Radar.js 和 export default class Radar { ... }。入口点定义为

module.exports = {
  entry: {
    "technology-radar": "./src/Radar.js",
    ...
  }
  ...
}

您似乎误解了包的发布和使用方式。

完全忽略 Webpack,标准 npm 模块将 main 设置为作为包根的 JS 文件,通常发布到 npm 的包是使用 Babel 编译的 发布之前。通常在发布 technology-radar 之前,您会使用像 babel-cli

这样的包
babel src -d lib

src目录中的所有内容编译成lib内的ES5。然后 你的 package.json#main 值应该是

"main": "./lib/index.js"

或者任何一个包都是你的包的概念根。在你的情况下可能是 Radar.js,但很难说。

因为您的 main 设置为 webpack.config.js,当您在实际应用程序中 运行 Webpack 时,您正在尝试捆绑 Webpack 本身 用于在浏览器中使用,它不起作用,因为它是一个 Node 应用程序。

如果您已经完成了上述操作并且有一个 technology-radar 包已经用 Babel 处理过,那么您的 sample 应用程序的配置与您已经拥有的差不多。