包括捆绑的IIFE模块

时间:2018-05-01 21:40:19

标签: javascript commonjs iife rollupjs

我在理解如何使用rollup.js捆绑iife模块时遇到了问题。 我尝试加载的模块定义为......

;(function (sax) {
    sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
    sax.SAXParser = SAXParser
    sax.SAXStream = SAXStream
    sax.createStream = createStream
    [...]
})(typeof exports === 'undefined' ? this.sax = {} : exports)

这是我的rollup.config.js

import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import globals from 'rollup-plugin-node-globals';
import babel from 'rollup-plugin-babel';

export default {
  input: 'index.js',
  output: {
    file: 'build/foo.js',
    format: 'umd',
    name: 'foo'
  },
  moduleContext: {
    'node_modules/sax/lib/sax.js': 'window'
  },
  plugins: [
    globals(),
    nodeResolve({
      jsnext: true,
      main: true
    }),

    commonjs({
      include: [
        'node_modules/**',
      ],
      namedExports: {
        'node_modules/sax/lib/sax.js': 'default'
      },
      ignore: [ 'conditional-runtime-dependency' ]
    }),

    babel({
      exclude: 'node_modules/**'
    }),
  ]
};

我的代码是用...导入依赖项

import sax from "sax";

但是rollup -c失败了:

[!] Error: 'default' is not exported by node_modules/sax/lib/sax.js

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

在commonjs namedExports中,您必须使用用于导入的字符串,而不是文件目录:

commonjs({
  include: [
    'node_modules/**',
  ],
  namedExports: {
    sax: ['default']
  }
}),