56876


**質問の主旨**  
現在、Reactを勉強中で本を読み進めてチャットアプリを作成しています。ですが、webpackのコンパイルでよく理解できないエラーが出てしまいうまくいきません。  
ブラウザは立ち上がるのですが、画面が白いまま、エラーが出ます。  
初心者なので、webpack周りのエラーのことを調べてみても結局よくわからないままです。

開発環境は以下の通りです。

**インストールしたライブラリ**

  * Node.js
  * Express
  * React
  * Socket.io / WebSocket

**ディレクトリ**

[code]

    -chat
     -public
      -bundle.js
      -index.html
     -src
      - index.js
     - chat-server.js
     - package.json
     - package-lock.json
     -webpack.config.js
    
[/code]

**原因が分からないエラー**

[code]

    ERROR in ./src/index.js
    Module build failed (from ./node_modules/babel-loader/lib/index.js):
    Error: Plugin/Preset files are not allowed to export objects, only functions. In C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-preset-es2015\lib\index.js
        at createDescriptor (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-descriptors.js:178:11)
        at items.map (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-descriptors.js:109:50)
        at Array.map (<anonymous>)
        at createDescriptors (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-descriptors.js:109:29)
        at createPresetDescriptors (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-descriptors.js:101:10)
        at passPerPreset (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-descriptors.js:58:96)
        at cachedFunction (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\caching.js:33:19)
        at presets.presets (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-descriptors.js:29:84)
        at mergeChainOpts (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-chain.js:320:26)
        at C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-chain.js:283:7
        at buildRootChain (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\config-chain.js:68:29)
        at loadPrivatePartialConfig (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\partial.js:85:55)
        at Object.loadPartialConfig (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\@babel\core\lib\config\partial.js:110:18)
        at Object.<anonymous> (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:144:26)
        at Generator.next (<anonymous>)
        at asyncGeneratorStep (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:3:103)
        at _next (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:5:194)
        at C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:5:364
        at new Promise (<anonymous>)
        at Object.<anonymous> (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:5:97)
        at Object._loader (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:224:18)
        at Object.loader (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:60:18)
        at Object.<anonymous> (C:\Users\haruk\Documents\study\study-mcoding\11-React\chat\node_modules\babel-loader\lib\index.js:55:12)
    npm ERR! code ELIFECYCLE
    npm ERR! errno 2
    npm ERR! chat@1.0.0 build: `webpack`
    npm ERR! Exit status 2
    npm ERR!
    npm ERR! Failed at the chat@1.0.0 build script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\haruk\AppData\Roaming\npm-cache\_logs\2019-07-22T10_04_30_153Z-debug.log
    
    
[/code]

webpack.config.json

[code]

    const path = require('path')
    
    module.exports = {
        mode: 'development',
        entry: path.join(__dirname,'src/index.js'),
        output: {
            path: path.join(__dirname,'public'),
            filename: 'bundle.js'
        },
        devtool: 'inline-source-map',
        module: {
            rules: [
                {
                    test: /.js$/,
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    options: {
                        presets: ['es2015','react','env']
                    }
                }
            ]
        }
    
    }
    
[/code]

package.json

[code]

    {
      "name": "chat",
      "version": "1.0.0",
      "description": "",
      "main": "public/bundle.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "express": "^4.17.1",
        "react": "^16.8.6",
        "react-dom": "^16.8.6",
        "socket.io-client": "^2.2.0",
        "socketio": "^1.0.0"
      },
      "devDependencies": {
        "@babel/core": "^7.5.5",
        "@babel/preset-react": "^7.0.0",
        "babel-core": "^6.26.3",
        "babel-loader": "^8.0.6",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^4.36.1",
        "webpack-cli": "^3.3.6"
      }
    }
    
[/code]

**追記**

index.html

[code]

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="./bundle.js"></script>
    </body>
    </html>
    
[/code]

chat-server.js

[code]

    //リアルタイムチャットのサーバ
    
    const express = require('express')
    const app = express()
    const server = require('http').createServer(app)
    const portNo = 3001
    server.listen(portNo, () => {
        console.log('open server',`http://localhost:${portNo}`)
    })
    
    app.use('/public',express.static('./public'))
    app.get('/',(req,res) => {
        res.redirect(302,'/public')
    })
    
    const socketio = require('socket.io')
    const io = socketio.listen(server)
    
    io.on('connection',(socket) => {
        console.log('connet user', socket.client.id)
        socket.on('chat-msg' ,(msg) => {
            console.log('message',msg)
            io.emit('chat-msg',msg)
        })
    })
    
[/code]

index.js

[code]

     import React from 'react'
     import ReactDOM from 'react-dom'
     import socketio from 'socket.io-client'
    
     const socket = socketio.connect('http://localhost:3001')
    
     class ChatForm extends React.Component{
         constructor(props){
            super(props)
            this.state = {
                name: '',
                message: ''
            }
         }
         nameChanged(e){
             this.setState({message: e.target.value})
         }
         messageChanged(e){
             this.setState({message: e.target.value})
         }
    
         send(){
             socket.emit('chat-msg',{
                 name: this.state.name,
                 message: this.state.message
             })
             this.setState({message: ''})
         }
         render(){
             return(
                 <div>
                     <p>名前: <br /></p>
                     <input value={this.state.name} onChange={e => this.nameChanged(e)} /><br />
                     <p>メッセージ: <br /></p>
                     <input value={this.state.message} onChange={e => this.messageChanged(e)}/><br />
                     <button onClick={e => this.send()}>送信</button>
                 </div>
             )
         }
     }
    
     class ChatApp extends React.Component{
         constructor(props){
             super(props)
             this.state = {
                 logs: []
             }
         }
    
         componentDidMount(){
             socket.on('chat-msg', (obj) => {
                 const logs2 = this.state.logs
                 obj.key = 'key_' + (this.state.logs.length + 1)
                 console.log(obj)
                 logs2.unshift(obj)
                 this.setState({logs: logs2})
             })
         }
         render(){
             const messages = this.state.logs.map(e => (
                 <div key={e.key}>
                     <span>{e.name}</span>
                     <span>: {e.message}</span>
                 </div>
             ))
             return (
                 <div>
                     <h1>chat</h1>
                     <ChatForm />
                     <div>{messages}</div>
                 </div>
             )
         }
     }
    
     ReactDOM.render(
         <ChatApp />,
         document.getElementById('root')
     )
    
[/code]

以上です。ご回答宜しくお願い致します。


CC BY-SA 4.0
2019-07-22T10:29:19.833
56816
2019-07-25T04:17:13.070
2019-07-25T04:17:13.070
32986
question
reactjs webpack babeljs
webpackのビルドをしても,ローカルの開発環境でエラーが出てしまいブラウザに何も表示されません


`package.json` の `devDependencies` プロパティから、質問者さんが Babel 7 を使用しているとわかります。そして
Babel 7 からは、
**すべてのパッケージがスコープ付きパッケージへ変更されました**[[1]](https://babeljs.io/docs/en/v7-migration#scoped-
packages)。これにより、パッケージ名は `babel-*` から `@babel/*` に切り替わることになります。

この変更が行なわれた主な理由は、下記引用の第二段落にあるとおり、 **パッケージ名の不当な占拠** 、 **コミュニティプラグインとの明確な区別** や、
**命名に関する問題** などを解消するためです。これに関してより詳細が知りたい場合は、 [npm | policies |
disputes](https://www.npmjs.com/policies/disputes#squatting) や [Nearing the
7.0 Release · Babel](https://babeljs.io/blog/2017/12/27/nearing-
the-7.0-release.html#renames-scoped-packages-babel-x) を参考にしてください。

> ### Scoped Packages[[1]](https://babeljs.io/docs/en/v7-migration#scoped-
> packages)
>
> The most important change is finally switching all packages to scoped
> packages (the folder names in the monorepo are not changed but the name in
> its `package.json` is).
>
> This means there will be no more issues with accidental/intentional name
> squatting, a clear separation from community plugins, and a simpler naming
> convention.
>
> Your dependencies will need to be modified like so:
>
> `babel-cli` -> `@babel/cli`. For us, we basically started by replacing
> `babel-` with `@babel/`.

* * *

以上を踏まえたうえで `package.json` や `webpack.config.js` を見直すと、パッケージ名が `@babel/*` ではなく、
`babel-*` であるものが存在するとわかります。よって、これらのパッケージ名を修正し、再度 `npm install`
を行なえば、質問文のエラーは解消されます。

**`package.json`**

[code]

    {
      "name": "chat",
      "version": "1.0.0",
      "description": "",
      "main": "public/bundle.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "express": "^4.17.1",
        "react": "^16.8.6",
        "react-dom": "^16.8.6",
        "socket.io-client": "^2.2.0",
        "socketio": "^1.0.0"
      },
      "devDependencies": {
        "@babel/core": "^7.5.5",
        "@babel/preset-react": "^7.0.0",
        "@babel/preset-env": "^7.5.5",
        "babel-loader": "^8.0.6",
        "webpack": "^4.36.1",
        "webpack-cli": "^3.3.6"
      }
    }
    
[/code]

**`webpack.config.js`**

[code]

    const path = require('path')
    
    module.exports = {
        mode: 'development',
        entry: path.join(__dirname,'src/index.js'),
        output: {
            path: path.join(__dirname,'public'),
            filename: 'bundle.js'
        },
        devtool: 'inline-source-map',
        module: {
            rules: [
                {
                    test: /.js$/,
                    loader: 'babel-loader',
                    exclude: /node_modules/,
                    options: {
                        presets: ['@babel/preset-env','@babel/preset-react']
                    }
                }
            ]
        }
    }
    
[/code]


CC BY-SA 4.0
2019-07-25T03:53:24.077
56876
2019-07-25T03:53:24.077
32986
56816
answer