在 webpack -p 上的 ./app/index.js 中存在错误

ERROR in ./app/index.js on webpack -p

本文关键字:js 存在 错误 index app webpack 上的      更新时间:2023-09-26

所以我上周被告知我需要学习反应.js。 我的JavaScript是有限的,但到底是什么。

我正在尝试通常的"Hello World"项目来感受一下。

当我使用以下索引运行 webpack -p 时.js文件它工作正常:

index.js
var app = document.getElementById('app');
app.innerHTML = 'Hello World!'

但是当我更改索引时.js更改为以下内容:

index.js
var React = require('react');
var ReactDOM = require('react-dom');
var HelloWorld = react.createClass({
    render: function() {
        return (
            <div>Hello World</div>
        )
    }
});
ReactDOM.render(
    <HelloWorld/>,
    document.getElementById('app')
)

我收到以下错误:

C:'Programming'reactFiles>npm run production
> reactfiles@1.0.0 production C:'Programming'reactFiles
> webpack -p
Hash: 21e367e251c35209471c
Version: webpack 1.12.14
Time: 692ms
          Asset       Size  Chunks             Chunk Names
index_bundle.js  289 bytes       0  [emitted]  main
     index.html  315 bytes          [emitted]
   [0] multi main 28 bytes {0} [built] [1 error]
    + 1 hidden modules
ERROR in ./app/index.js
Module build failed: SyntaxError: C:/Programming/reactFiles/app/index.js: Unexpected token (7:12)
   5 |     render: function() {
   6 |         return (
>  7 |             <div>Hello World</div>
     |             ^
   8 |         )
   9 |     }
  10 | });
     at parser.pp //.......for about 30 lines.  I can add them if it helps
@ multi main
Child html-webpack-plugin for "index.html":
        + 3 hidden modules

我的包.json:

{
  "name": "reactfiles",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "production": "webpack -p",
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "babel-core": "^6.6.5",
    "babel-loader": "^6.2.4",
    "babel-preset-react": "^6.5.0",
    "html-webpack-plugin": "^2.9.0",
    "webpack": "^1.12.14",
    "webpack-dev-server": "^1.14.1"
  }
}

webpack.config.js:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
})
module.exports = {
    entry: [
        './app/index.js'
    ],
    output: {
        path: __dirname + '/dist',
        filename: "index_bundle.js"
    },
    module: {
        loaders: [
            {test: /'.js$/, exclude: /node_modules/, loader: "babel-loader"}
        ]
    },
    plugins: [HtmlWebpackPluginConfig]
}

我见过其他类似的问题,但没有找到有效的答案。

有什么想法吗?

你的 babel-loader 缺少配置。

{
    test: /'.js$/,
    loader: "babel",
    exclude: /node_modules/,
    query: {
        presets: ["react"]
    }
}

瞧,它有效。:)

参考: https://github.com/babel/babel-loader#usage

编辑:

刚刚意识到,我有点不解释就把它扔进去了:指定加载器时,不需要写完整的加载器名称。您可以从名称中省略-loader,无论如何 Webpack 都会找到它!