首页 > 解决方案 > Fetch 不能在 webpack 中使用 babel 加载器

问题描述

我正在尝试使用 fetch 到 api 来发出 ajax 请求。当我运行 npm build 我得到这个错误

ERROR in ./src/js/index.js 14:7
Module parse failed: Invalid regular expression flag (14:7)
You may need an appropriate loader to handle this file type.
| document.body.appendChild(c);
|
> fetch(/api/post/read.php)
| .then(res => res.json())
| .then((data) => {

我的 webpack 配置 -

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
      app:'./src/js/index.js',
      test:'./src/js/test2.js'
    },
    devtool: 'source-map ',
    devServer: {
      contentBase: './dist',
      compress: true,
      port: 8080
    },
    plugins: [
      new HtmlWebpackPlugin({
          title: 'Menu',
          template: './src/views/index.ejs',
      })
    ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
          {
           test: /\.scss$/,
           use: [
            'style-loader',
            'css-loader',
            'sass-loader'
          ]
        },
        {
          test: /\.jsnpm$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          query: {
            presets: ['@babel/preset-env']
          }
        },
        {
          test: /\.(png|svg|jpg|gif)$/,
           use: [
           'file-loader'
          ]
        }
      ]
   },
};

和我的 package.json -

{
  "name": "menu",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open",
    "build": "webpack"
  },
  "author": "aioy",
  "license": "MIT",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "babel-loader": "^8.0.5",
    "css-loader": "^2.1.0",
    "file-loader": "^3.0.1",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.11.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.28.2",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.14"
  }
}

我还需要添加哪些其他模块才能使用 fetch?我正在使用 fetch 访问与前端 webpack 文件位于同一目录中的本地 api 服务器,这是否也会导致问题?

标签: javascriptwebpackecmascript-6fetchbabeljs

解决方案


推荐阅读