为什么当TypeScript编译器没有找到模块时,Webpack无法找到模块?

one*_*ree 6 typescript webpack typescript2.0 fuse.js

我正在尝试在我的TypeScript应用程序中使用Fuse.我正在导入模块类型import * as fuselib from 'fuse.js';.编译好tsc.我遇到的问题是我使用时构建项目webpack --config config/webpack.prod.js --progress --profile --bail.

我收到错误Cannot find module 'fuse.js'.该保险丝分型,可以发现在这里.看看我编译的JS,我找不到这个词fuse.js,所以我猜测Webpack正在破坏这个名字.我试着忽略关键字fuse.jsUglifyJsPlugin,但是这并没有帮助.

我的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)
                }
            })
    ]
});
Run Code Online (Sandbox Code Playgroud)

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'
        })
    ]
};
Run Code Online (Sandbox Code Playgroud)

为了使Webpack看模块,我缺少什么fuse.js

Alu*_*dad 7

更新

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

回答

好的,这是发生了什么以及为什么.

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

它包含一个包含类声明的模块声明,可能是为了描述模块的形状,但不导出类.

declare module 'fuse.js' {
  class Fuze // missing one of: export, export =, export default
}
Run Code Online (Sandbox Code Playgroud)

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

进一步向下Fuse/index.d.ts宣布其全球性

declare const Fuse;
Run Code Online (Sandbox Code Playgroud)

据推测,基于约定和阅读实际JavaScript中的注释,这意味着具有与从模块导出的内容相同的形状.不幸的是,它any的类型与尝试模块的类型不同,因为它无效,也没有Fuse被困在所述模块中但未导出的类的类型...

那么为什么会出错呢?你可能在你的程序中有以下某个地方:import'fuver'; 从'fuse'导入保险丝; 从'fuse'导入*作为保险丝;

其次是一些使用Fuse喜欢

const myFuse = new Fuse();
Run Code Online (Sandbox Code Playgroud)

这将导致fuseTypeScript发出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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

考虑使用修复程序向维护者发送拉取请求.

用法:

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

CommonJS,AMD或UMD风格

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

const myFuseOptions: Fuse.FuseOptions = {
  caseSensitive: false
};
const myFuse = new Fuse([], myFuseOptions);
Run Code Online (Sandbox Code Playgroud)

ES与CommonJS互操作风格

(当使用"module": "system""allowSyntheticDefaltImports")与SystemJS,最近的Webpacks,或通过Babel管道.从typescript 2.7开始,您也可以使用新--esModuleInterop标志而无需任何其他模块工具或转换器.

import Fuse from 'fuse.js';

const myFuseOptions: Fuse.FuseOptions = {
    caseSensitive: false
};
const myFuse = new Fuse([], myFuseOptions);
Run Code Online (Sandbox Code Playgroud)

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