JSX:您可能需要适当的加载程序来处理此文件类型

时间:2019-05-13 11:44:15

标签: reactjs webpack babel babel-loader

尝试使用以下内容配置我的构建环境以解析React和JSX。但是我很害怕“您可能需要适当的加载程序来处理此文件类型”:

wp.js

class Welcome extends React.Component {
  render() {
    return <h1>Hello World from React boilerplate</h1>;
  }
}

ReactDOM.render(<Welcome />, document.getElementById('root'));

index.js

import React from 'react'
import ReactDOM from 'react-dom';
import './wp.js';

webpack.config.js

....
{
        test: /js\\\.*js$/,
        use:
        [
            {
                loader:'script-loader'
            },
            {
                loader:'babel-loader'
            }
        ]
}
....

package.json

....
"devDependencies": {
    "@babel/core": "^7.4.4",
    "@babel/preset-env": "^7.4.4",
    "@babel/preset-react": "^7.0.0",
    "autoprefixer": "^9.4.7",
    "babel-loader": "^8.0.6",
    "bootstrap": "^4.3.1",
    "clean-webpack-plugin": "^1.0.1",
    "copy-webpack-plugin": "^5.0.0",
    "css-loader": "^2.1.0",
    "file-loader": "^3.0.1",
    "js-offcanvas": "^1.2.9",
    "node-sass": "^4.11.0",
    "popper.js": "^1.14.7",
    "postcss-loader": "^3.0.0",
    "precss": "^4.0.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "sass-loader": "^7.1.0",
    "script-loader": "^0.7.2",
    "style-loader": "^0.23.1",
    "webpack": "^4.29.5",
    "webpack-cli": "^3.2.3"
  }
....

我还将babel预设放在这里(以及.babelrc文件中)

....
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  }
....

我知道我会缺少一些非常基本的东西,但看不到它。预先谢谢你!

1 个答案:

答案 0 :(得分:0)

这是因为您的JSX规则实际上不是在寻找.jsx个文件,而只是寻找.js个文件。您的“测试”正则表达式是错误的。

这是从webpack配置中摘录的,该配置使用babel加载JSX文件:

  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    use: ['babel-loader']
  }

在Google周围搜索基本的React + Webpack设置文章/帖子,以查看webpack.config.js文件的完整示例