简体   繁体   English

使用ES6,Webpack和Babel导入UMD样式模块

[英]Importing UMD style module with ES6, Webpack, and Babel

I have found a few StackOverflow questions related to this but none that match nor fix my problem. 我发现了一些与此相关的StackOverflow问题,但没有一个匹配或解决了我的问题。

I am writing a library in ES6 that is intended to be used in the browser and on the server. 我正在用ES6编写一个库,该库打算在浏览器和服务器上使用。 I have found a few HTTP request libraries that can be use on the server or browser ( popsicle , axios ). 我发现,可以在服务器或浏览器(使用几个HTTP请求库冰棒爱可信 )。 I have successfully used these libraries in both places but am having some issues when importing them in my source and using the outputted webpacked file. 我已经在两个地方都成功使用了这些库,但是在将它们导入到源中并使用输出的webpacked文件时遇到了一些问题。

My ES6 source file where I am importing the axios library is 我要导入axios库的ES6源文件是

import axios from 'axios';

export default {
    go: function() {
        return axios.get('http://www.google.com');
    }
};

My webpack config is 我的webpack配置是

var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var WebpackNotifierPlugin = require('webpack-notifier');
var path = require('path');
var env = require('yargs').argv.mode;

var libraryName = 'library';
var source = '/src/test.js';

var plugins = [],
    outputFile;

if (env === 'build') {
    plugins.push(new UglifyJsPlugin({
        minimize: true
    }));
    outputFile = libraryName + '.min.js';
} else {
    outputFile = libraryName + '.js';
    plugins.push(new WebpackNotifierPlugin())
}

var config = {
    entry: __dirname + source,
    devtool: 'source-map',
    output: {
        path: __dirname + '/lib',
        filename: outputFile,
        library: libraryName,
        libraryTarget: 'umd',
        umdNamedDefine: true
    },
    externals: {},
    module: {
        loaders: [{
            test: /(\.jsx|\.js)$/,
            loader: 'babel',
            exclude: /(node_modules|bower_components)/
        }, {
            test: /(\.jsx|\.js)$/,
            loader: "eslint-loader",
            exclude: /node_modules/
        }]
    },
    resolve: {
        root: path.resolve('./src'),
        extensions: ['', '.js']
    },
    plugins: plugins
};

module.exports = config;

As you can see I am setting the libraryTarget to umd and umdNamedDefine to true 如您所见,我正在将libraryTarget设置为umd并将umdNamedDefine设置为true

And my .bablerc is 而我的.bablerc

{
  "presets": ["es2015"],
  "plugins": ["add-module-exports", "babel-plugin-add-module-exports"]
}

I am able use my library in the browser by including it in a script tag but I am not able to use it when importing with node. 通过在script标签中包含库,我可以在浏览器中使用它,但是在与node一起导入时,我将无法使用它。 I get an XMLHttpRequest is not defined . 我得到一个XMLHttpRequest is not defined The axios library says it uses XMLHttpRequest when on the browser and http when running in node but for some reason it is not detecting it is being run on the server. axios库表示在浏览器上使用XMLHttpRequest,在节点上运行时使用http,但是由于某种原因,它没有检测到它正在服务器上运行。 I am having this issues with a few UML libraries so believe it is not the specific package. 我在一些UML库中遇到了这个问题,因此相信它不是特定的程序包。 Also, since I can use these libraries in node ES5 without running webpack or babel I am led to assume it is a configuration issue with webpack. 另外,由于我可以在不运行webpack或babel的情况下在节点ES5中使用这些库,因此我被认为是webpack的配置问题。

How can I import these UMD style libraries in ES6 and generate a library with Webpack and Babel that can be used on the server and browser? 如何在ES6中导入这些UMD样式库,并使用Webpack和Babel生成可在服务器和浏览器上使用的库?

To make your package as small as possible I'd recommend using the Fetch API. 为了使您的程序包尽可能小,我建议使用Fetch API。 A UMD library has the three types of consumers where fetch comes in handy; UMD库具有三种方便使用的消费者类型。

  • Node.js - has not implemented but can use node-fetch to polyfill common behaviour using only node libraries (no heavy dependencies like superagent, unirest and axios etc - these add security concerns as well as bloat!). Node.js-尚未实现,但可以使用node-fetch来仅使用节点库来填充常见行为(不存在诸如superagent,unirest和axios等繁重的依赖关系-这些都增加了安全隐患,而且让人肿!)。
  • Browser - Fetch is a WHATWG standard and is available in most modern browsers but might require an npm package such as whatwg-fetch to polyfill older browsers 浏览器-Fetch是WHATWG标准,可在大多数现代浏览器中使用,但可能需要npm软件包(如whatwg-fetchwhatwg-fetch旧版浏览器
  • Isomorphic/Universal - the same javascript running in browser and node.js which you find in progressive web apps.They need to use a library called isomorphic-fetch to load either whatwg-fetch or the node.js version of fetch. Isomorphic / Universal-在渐进式Web应用程序中的浏览器和node.js中运行的相同javascript,它们需要使用一个称为isomorphic-fetch的库来加载whatwg-fetch或node.js版本的fetch。

It should be handled by the projects consumer though so README should include instructions to each of the three types of users above. 尽管它应该由项目使用者处理,所以自述文件应包括针对上述三种类型的用户的说明。

Node.js and isomorphic instructions are basically as below. Node.js和同构指令基本上如下。

require(‘node-fetch’); // or require(‘isomorphic-fetch’)
const MyUMDLibrary = require('my-umd-library');
const myUMDLibrary = new MyUMDLibrary();

For browsers using the script from cdn they could also load a fetch polyfill before https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js . 对于使用cdn脚本的浏览器,他们还可以在https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js之前加载提取polyfill。

I'd suggest using rollup for a UMD library ( see a working example I've contributed before for a UMD library ) but Webpack shouldn't be a problem either. 我建议对UMD库使用汇总请参阅我之前为UMD库提供的工作示例 ),但Webpack也不应该成为问题。 Rather than trying to include the 'axios' dependency within your application with Fetch you can leave it out and allow your users to decide how they will load the package (ie module loader, script, require). 与其尝试在Fetch中不将“ axios”依赖项包含在应用程序中,还可以忽略它,让用户决定如何加载程序包(即模块加载器,脚本,require)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM