使用webpack加载.jsx文件

时间:2016-07-17 11:29:27

标签: javascript reactjs webpack jsx

我在使用.jsx加载webpack文件时遇到问题。 我有webpack.config.js

var webpack = require('webpack');

module.exports = {
    entry: "./static/js/storage/src/index.js",
    output: {
        path: './static/js/storage/public/',
        publicPath: "public/",
        filename: "bundle.js"
},

resolve: {
    extensions: ['', '.js', '.jsx']
},

module: {
    loaders: [
        {
            test: /\.js$/,
            loader: "babel-loader",
            exclude: [/node_modules/, /public/],
            query: {
                plugins: ['transform-runtime'],
                presets: ['es2015', 'stage-0', 'react']
            }
        },
        {
            test: /\.jsx$/,
            loader: "react-hot!babel",
            exclude: [/node_modules/, /public/]
        }
    ]
}
};

我有这个包用于我的应用程序:

"dependencies": {
    "jquery": "^3.1.0",
    "react": "^15.2.1",
    "react-dom": "^15.2.1"
},
    "devDependencies": {
    "autoprefixer-loader": "^3.2.0",
    "babel": "^6.5.2",
    "babel-core": "^6.10.4",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-polyfill": "^6.9.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babel-runtime": "^6.9.2",
    "css-loader": "^0.23.1",
    "file-loader": "^0.9.0",
    "json-loader": "^0.5.4",
    "jsx-loader": "^0.13.2",
    "react": "^15.2.1",
    "react-hot-loader": "^1.3.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack": "^1.13.1"
}

当我尝试在控制台中运行webpack时出现此错误:

  

模块解析失败:   /static/js/storage/src/components/StorageApp.jsx   意外的令牌(12:12)您可能需要一个合适的加载器来处理   这个文件类型。

我的webpack无法加载jsx文件。我认为问题出在我的jsx加载器中。但我不知道究竟是什么问题。

我尝试使用react-hot,babel loader和jsx-loader与预设,但没有错误在所有情况下是相同的。 这些装载机无法工作:

test: /\.jsx$/,
    loader: 'babel',
    query: {
        presets: ['react', 'es2015']
},

有人可以帮忙解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

由于您在webpack设置中排除了'public'文件夹,编译器无法解析.jsx文件。

在您的网络包文件下面更新

exclude: [/node_modules/, /public/],

exclude: [/node_modules/],

用于.js和.jsx加载器。

答案 1 :(得分:0)

试试这个

loaders: [
        {
            test: /\.jsx?$/,
            loader: "babel-loader",
            exclude: [/node_modules/, /public/],
            query: {
                plugins: ["react-hot-loader/babel", 'transform-runtime'],
                presets: ['es2015', 'stage-0', 'react']
            }
        }
    ]

答案 2 :(得分:0)

我通过在每个导入的组件中添加.jsx后缀来解决该问题,如下所示:

import Somthing from './Something.jsx'