首页 > 解决方案 > 带有 Babel 的 Webpack 在 Reactjs 中不起作用

问题描述

我正在尝试使用 webpack 和 babel 配置我的反应应用程序。我创建了如下所示的 webpack.config.js:

> var webpack = require("webpack"); var path = require("path"); var
> HtmlWebpackPlugin = require("html-webpack-plugin"); const VENDORLIBS =
> ["react", "react-dom"]; module.exports = {   mode: 'development',  
> entry: {
>     bundle: "./src/index.js",
>     vendor: VENDORLIBS   },   output: {
>     path: path.join(__dirname, "dist"),
>     filename: "[name].[chunkhash].js"   },   devtool:'inline-source-map',   module: {
>     rules: [
>       {
>         test: /\.js$/,
>         use: "babel-loader",
>         exclude: /node_modules/
>       },
>       {
>         test: /\.css$/,
>         use: ["style-loader", "css-loader"]
>       },
>       {
>         test: /\.scss$/,
>         use: "sass-loader"
>       }
>     ]   },   plugins: [
>     new webpack.optimize.CommonsChunkPlugin({
>       names: ["vendor", "manifest"]
>     }),
>     new HtmlWebpackPlugin({
>       template: "public/index.html"
>     })   ] };

我还创建了 .babelrc,它看起来像:

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

现在,当我使用 webpack 运行它时,出现如下错误:

>

 (function (exports, require, module, __filename, __dirname) {


SyntaxError: Invalid or unexpected token
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! eccomerce@1.0.0 test-build: `webpack`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the eccomerce@1.0.0 test-build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

请帮我解决这个问题,因为我被困得很厉害。提前致谢 !!

标签: reactjswebpackbabeljs

解决方案


我认为您的 webpack 条目:{} 可能会导致问题。

将其替换为entry: './src/index.js'

并确保您已安装所有 babel 要求:

@babel/core @babel/preset-env babel-loader

并参考Webpack Docs


推荐阅读