为什么 TypeScript 编译器找不到时 Webpack 找不到模块?

Why does Webpack fail to find a module when the TypeScript compiler doesn't?

我正在尝试在我的 TypeScript 应用程序中使用 Fuse。我正在使用 import * as fuselib from 'fuse.js'; 导入模块类型。使用 tsc 可以很好地编译。我 运行 遇到的问题是当我使用 webpack --config config/webpack.prod.js --progress --profile --bail.

构建项目时

我收到错误 Cannot find module 'fuse.js'Fuse 类型可以在 此处 找到。查看我编译的 JS,我找不到 fuse.js 这个词,所以我猜 Webpack 正在修改这个名字。我尝试忽略 UglifyJsPlugin 中的关键字 fuse.js,但这没有帮助。

我的 Webpack 配置很标准。

webpack.prod.js

var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = webpackMerge(commonConfig, {
    devtool: 'source-map',

    output: {
        path: helpers.root('dist'),
        publicPath: '/',
        filename: '[name].[hash].js',
        chunkFilename: '[id].[hash].chunk.js'
    },

    htmlLoader: {
        minimize: false // workaround for ng2
    },

    plugins: [
        new webpack.NoErrorsPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
            mangle: {
                keep_fnames: true,
                except: ['fuse.js']
            }
        }),
            new ExtractTextPlugin('[name].[hash].css'),
            new webpack.DefinePlugin({
                'process.env': {
                    'ENV': JSON.stringify(ENV)
                }
            })
    ]
});

webpack.common.js

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

module.exports = {
    entry: {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts'
    },

    resolve: {
        extensions: ['', '.js', '.ts', '.tsx'],
        modulesDirectories: ['src', 'node_modules']
    },

    module: {
        loaders: [
        {
            test: /\.ts$/,
            loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular2-router-loader']
        },
        {
            test: /\.html$/,
            loader: 'html'
        },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src', 'app'),
                loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
            },
                {
                    test: /\.css$/,
                    include: helpers.root('src', 'app'),
                    loader: 'raw'
                }
        ]
    },

    plugins: [
        // for materialize-css
        new webpack.ProvidePlugin({
            "window.jQuery": "jquery",
            "window._": "lodash",
            _: "lodash"
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),
        new HtmlWebpackPlugin({
            template: 'src/index.html'
        })
    ]
};

为了让 Webpack 看到模块 fuse.js,我缺少什么?

诀窍是提供对全局变量 Fuse 的访问。 它由 webpack 和 ProvidePlugin

完成

将以下插件添加到 webpack 插件数组:

    ...
    new webpack.ProvidePlugin({
        "Fuse": "fuse.js"
    })
    ...

更新

我根据这个答案为图书管理员问题写了新的声明。它应该与最新版本一起正常工作,因为它们随库一起提供。

回答

好的,这是正在发生的事情及其原因。

首先,Fuze/index.d.ts 试图将自己声明为全局外部模块和环境外部模块,但是这两种方法都不正确。这使得滥用,例如导致您的错误几乎是不可避免的。

它包含一个包含 class 声明的模块声明,大概是为了描述模块的形状,但 class 未导出。

declare module 'fuse.js' {
  class Fuze // missing one of: export, export =, export default
}

这意味着我无法正确导入模块,实际上在尝试从中导入值 and/or 类型时存在类型错误。

再往下 Fuse/index.d.ts 它声明了它的全局

declare const Fuse;

据推测,根据惯例并阅读实际 JavaScript 中的注释,这意味着与从模块导出的形状具有相同的形状。不幸的是,它的类型 any 既不是与尝试的模块相同的类型,因为它无效,也不是被困在所述模块内的 class Fuse 的类型但未导出...

那么为什么会出错呢?您的程序中可能有以下某处:

import 'fuse.js';

import Fuse from 'fuse.js';

import * as Fuse from 'fuse.js';

然后使用 Fuse

const myFuse = new Fuse();

这将导致 TypeScript 发出 Fuse fuse 的运行时表示的导入,以便您可以使用从模块导入的值。

要解决此问题,您可以使用全局 const Fuse 而不是将其导入任何地方。不幸的是,这不是我们想要的。作者几乎可以肯定是想在 Fuze/index.d.ts 中包含以下内容:

export = Fuse;

export as namespace Fuse;

declare class Fuse {
    constructor(list: any[], options?: Fuse.FuseOptions)
    search<T>(pattern: string): T[];
    search(pattern: string): any[];
}

declare namespace Fuse {
    export interface FuseOptions {
        id?: string;
        caseSensitive?: boolean;
        include?: string[];
        shouldSort?: boolean;
        searchFn?: any;
        sortFn?: (a: { score: number }, b: { score: number }) => number;
        getFn?: (obj: any, path: string) => any;
        keys?: string[] | { name: string; weight: number }[];
        verbose?: boolean;
        tokenize?: boolean;
        tokenSeparator?: RegExp;
        matchAllTokens?: boolean;
        location?: number;
        distance?: number;
        threshold?: number;
        maxPatternLength?: number;
        minMatchCharLength?: number;
        findAllMatches?: boolean;
    }
}

它声明了一个 class,它可以全局使用,供不使用模块的人使用,或者通过导入供使用模块的人使用。您可以使用上面的 UMD 样式声明来获得作者想要的打字体验。与库捆绑在一起的那个不提供类型信息,实际上在使用时会导致错误。

考虑 向维护者发送拉取请求和修复。

用法:

您可以通过以下方式使用此声明:

CommonJS、AMD 或 UMD 风格

import Fuse = require('fuse.js');

const myFuseOptions: Fuse.FuseOptions = {
  caseSensitive: false
};
const myFuse = new Fuse([], myFuseOptions);

具有 CommonJS 互操作风格的 ES

(当使用 "module": "system""allowSyntheticDefaltImports" 时)与 SystemJS,最近的 Webpacks,或者如果通过 Babel 管道。从打字稿 2.7 开始,您还可以使用新的 --esModuleInterop 标志,而无需任何其他模块工具或转译器。

import Fuse from 'fuse.js';

const myFuseOptions: Fuse.FuseOptions = {
    caseSensitive: false
};
const myFuse = new Fuse([], myFuseOptions);

从 typescript 2.7 开始,es 模块互操作现在可以直接在该语言中使用。这意味着您不需要使用 Babel 或 SystemJS 或 webpack 来编写正确的导入。