【问题标题】:Webpack with react modules giving unexpected token带有反应模块的 Webpack 给出了意外的令牌
【发布时间】:2015-10-01 04:35:08
【问题描述】:

一直在尝试使用 react-spin npm 模块,但是当我尝试使用 webpack 构建 bundle.js 时,收到以下错误:

Module parse failed: /Users/nir/browsewidget/node_modules/react-spin/src/main.js Line 29: Unexpected token <
You may need an appropriate loader to handle this file type.
|   render: function() {
|     return (
|       <span ref="container" />
|     );
|   }
 @ ./js/widget.jsx 4:14-35

我猜这个模块里面有jsx,但是我不明白为什么不能构建? react-spin 在构建 bundle 时是否需要一些额外的配置?

这是我完整的 webpack.config.js

module.exports = {
    entry: "./js/widget.jsx",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                    test: /\.jsx$/, 
                    loader: 'jsx-loader?insertPragma=React.DOM&harmony'
            }
        ]
    },
    externals: {
        //don't bundle the 'react' npm package with our bundle.js
        //but get it from a global 'React' variable
        'react': 'React'
    },
    resolve: {
        extensions: ['','.js','.jsx']
    }
};

【问题讨论】:

    标签: javascript npm reactjs webpack


    【解决方案1】:

    您的加载程序配置为仅转换以.jsx 结尾的文件:

     test: /\.jsx$/,
    

    (美元符号表示字符串结束。)

    你可以改成

    test: /\.jsx?$/,
    

    要同时转换 .js.jsx 文件,但是通过 JSX 加载程序运行 node_modules 中的每个 JavaScript 文件可能会相当慢。

    我相信您应该能够设置/node_modules/exclude 选项,然后为您关心的特定模块(react-spin)设置一个include 选项,但最好的解决方案是包不使用 JSX在已发布的 JavaScript 版本中——react-spin 的作者可能会接受拉取请求以达到这种效果。 (编辑:似乎已经有一个了,见thomasboyt/react-spin#3

    最后,react-spinis very small,所以你可以考虑在你自己的项目中自己实现它(这样你就不必担心 webpack 加载器问题)。

    【讨论】:

    • 谢谢,你说得很好。我最终在我的项目中包含了我自己的 react-spin。
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 2017-12-20
    相关资源
    最近更新 更多