【问题标题】:Problem importing external module with typescript (newb)使用打字稿(newb)导入外部模块时出现问题
【发布时间】:2018-09-14 16:23:46
【问题描述】:

我是 JS 的新手,尤其是 Typescript。我正在使用 npm 6.2.0 和 typescript 3.0.1。我正在尝试导入“文件保护程序”模块并使用它。它的index.d.ts 看起来像这样:

declare namespace FileSaver {
    function saveAs(data: Blob, filename?: string, disableAutoBOM?: boolean): void;
}
declare global {
    const saveAs: typeof FileSaver.saveAs;

    interface Window {
        saveAs: typeof FileSaver.saveAs;
    }
}
export = FileSaver;

当我在我的代码中导入它时(尝试了各种方法,这是最新的):

import { saveAs } from 'file-saver';
// later...
saveAs(blob, 'stuff.json');

汇总给我这个错误:

build/js/src/ngl.js → build/js/ngl.dev.js, build/js/ngl.esm.js...
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding 
  to external modules
file-saver (guessing 'fileSaver')

而且我的代码在浏览器 (Chrome) 中不起作用。我在运行时得到这个:

viewer.js:915 Uncaught TypeError: Cannot read property 'saveAs' of undefined
    at Viewer.__render (viewer.js:915)
    at Viewer.render (viewer.js:947)
    at viewer.js:745

这是我的rollup.config.js(稍微缩短为 SO):

import buble from 'rollup-plugin-buble';
import json from 'rollup-plugin-json';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

var path = require('path');
var pkg = require('./package.json');
var external = Object.keys(pkg.dependencies);

...

export default {
  input: 'build/js/src/app.js',
  plugins: [
    resolve({
      jsnext: true,
      main: true
    }),
    commonjs({
      namedExports: {
        'node_modules/chroma-js/chroma.js': [ 'scale' ],
        'node_modules/signals/dist/signals.js': [ 'Signal' ],
        'node_modules/sprintf-js/src/sprintf.js': [ 'sprintf' ]
      }
    }),
    json(),
    buble()
  ],
  output: [
    {
      file: "build/js/app.dev.js",
      format: 'umd',
      name: 'App',
      sourcemap: true
    },
    {
      file: "build/js/app.esm.js",
      format: 'es',
      name: 'App',
      sourcemap: true
    }
  ],
  external: external
};

【问题讨论】:

  • 请将您的rollup.config.js 添加到问题中。
  • @MattMcCutchen,添加了它

标签: javascript typescript import export


【解决方案1】:

尝试从rollup.config.js 中删除external 选项。这个选项告诉 Rollup 应该从包中省略 file-saver 模块,因为它将在您的目标环境中可用;在浏览器中,情况并非如此。

【讨论】:

  • 谢谢!做到了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 2012-12-28
  • 2016-07-13
  • 2020-02-05
相关资源
最近更新 更多