使用typescript(newb)导入外部模块时出现问题

问题描述 投票:0回答:1

我是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
};
javascript typescript import export
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.