带有react-hot-loader错误的Typescript找不到名称__REACT_HOT_LOADER __

时间:2017-11-17 10:55:50

标签: javascript typescript webpack react-hot-loader

我是打字稿的新手,我尝试使用webpack 3,react-hot-loader和awesome-typescript-loader配置一个小应用程序。到目前为止,我收到了两个我无法理解的错误。

第一个错误是:TS2304: Cannot find name '__REACT_HOT_LOADER__'

第二个错误是TS2304: Cannot find name '__webpack_exports__'

这是我的.tsconfig:

{
    "compilerOptions": {
        "outDir": "./public/",  
        "strictNullChecks": true,  
        "module": "es6",           
        "jsx": "react",            
        "target": "es5",           
        "allowJs": true,
        "moduleResolution": "node" 
    },
    "include": [
        "./src/"
    ]
}

这是我的webpack.config.js

require('dotenv').config();
var webpack = require('webpack');
var path = require('path');

var srcPath = path.join(__dirname, '/src')
var distPath = path.join(__dirname, '/public');

const config = {
    output: {
        path: distPath,
        publicPath: '/public',
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx']
    },
    module: {
        rules: [
            {
                test: /\.(j|t)sx?$/,
                exclude: /node_modules/,
                use: 'awesome-typescript-loader'
            },
            { 
                enforce: "pre", 
                test: /\.js$/, 
                loader: "source-map-loader" 
            }
        ]
    },
    context: srcPath,
    plugins: [
        new webpack.NamedModulesPlugin(),
        new webpack.EnvironmentPlugin(['NODE_ENV'])
    ]
};

// Development Environment
if (process.env.NODE_ENV === 'development') {
    config.entry = [
        'react-hot-loader/patch',
        'webpack-hot-middleware/client?noInfo=false',
        path.join(srcPath, '/index.tsx')
    ]

    config.module.rules.push(
        {
            test: /\.tsx?$/,
            exclude: /node_modules/,
            loader: 'react-hot-loader/webpack'
        }
    )

    config.plugins.push(
        new webpack.HotModuleReplacementPlugin()
    )
}

// Production Environment
if (process.env.NODE_ENV === 'production') {
    config.entry = [
        path.join(srcPath, '/index.tsx')        
    ];

    config.plugins.push(
        new webpack.optimize.UglifyJsPlugin()        
    )
}

module.exports = config;

我尝试了无数不同的配置,甚至挖掘了反应热链接器和webpack的源代码,似乎无法弄清楚为什么它不能识别这些变量。如果我将环境切换到生产并绕过热重新加载,我也有0个问题,所以它让我觉得第二个错误与第一个错误有关。

我错过了什么? (我确定它在我面前,我只是没有看到它)

1 个答案:

答案 0 :(得分:2)

您必须添加' react-hot-loader / webpack'作为ts,js,tsx,jsx文件的第一个加载器。因此,编辑您的webpack.config.js文件并替换以下行:

        {
            test: /\.(j|t)sx?$/,
            exclude: /node_modules/,
            use: 'awesome-typescript-loader'
        }

以下行:

        {
            test: /\.(j|t)sx?$/,
            exclude: /node_modules/,
            loaders: ['react-hot-loader/webpack','awesome-typescript-loader']
        }