使用带有babel和webpack

时间:2017-12-29 17:44:30

标签: javascript reactjs webpack babel

我在Chrome开发者工具上收到此错误: “未捕获参考:需求未定义”

webpack.config

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/app.js',
    output: {
        filename: 'app.js',
        path: __dirname + "public/scripts"
    },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: "babel-loader",
                exclude: /node_modules/,
                query: {
                    presets: ["env", "react"]
                }
            }
        ]
    }
};

的package.json

{
  "name": "widget",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Diogo Matias",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "npm": "^5.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-google-maps": "^9.4.3",
    "react-leaflet": "^1.7.8"
  },
  "devDependencies": {
    "webpack": "^3.10.0"
  }
}

此错误来自我的源javascript文件中的导入:

 import {GoogleMap, Marker} from "react-google-maps";

我使用cdn进行反应和反应。我习惯使用live-server而且我是webpack的新手。我在根目录下运行webpack-dev-server。 希望这足以帮助我。

感谢。

1 个答案:

答案 0 :(得分:0)

这是帮助您入门的最低配置。问题npm run start在端口9000上显示webpack-dev-server。您的配置中缺少babel-core

项目结构

├── build
│   └── index.html
├── package.json
├── src
│   └── app.js
└── webpack.config.js

的package.json

{
  "name": "widget",
  "version": "1.0.0",
  "description": "Get started with Webpack!",
  "scripts": {
    "build": "webpack",
    "start": "webpack-dev-server"
  },
  "author": "Diogo Matias",
  "license": "ISC",
  "dependencies": {
    "leaflet": "^1.2.0",
    "prop-types": "^15.5.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-google-maps": "^9.4.3",
    "react-leaflet": "^1.7.8"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.9.7"
  }
}

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build')
  },
  devServer: {
    contentBase: path.join(__dirname, 'build'),
    compress: true,
    port: 9000
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: "babel-loader",
        exclude: /node_modules/
      }
    ]
  }
};

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 3 Chrome versions"]
      }
    }]
  ]
}

建立/ index.html中

<html lang="en">
  <head>
    <meta charset="utf-8">
  </head>

  <body>
    <div id="root"></div>
    <script src="bundle.js"></script>
  </body>
</html>