Webpack 4基本React js hello world失败,“模块解析失败:意外令牌”

loading...


1

Update:

代码推到 https://github.com/gsouvik/react_spa_experiment

Initial Post:

我知道那里有数百个线程,有些在webpack配置中有拼写错误,有些在错误的方式中使用了加载器,有些已经解决了,有些仍然打开 . 但经过多次尝试后,我仍然无法使用Webpack 4,React js这个简单的“Hello World” .

What I did

我一行一行地关注这个视频教程:React & Webpack 4 from scratch

My package.json

{
  "name": "my_react_experiment_2",
  "version": "1.0.0",
  "description": "Basic react with webpack ",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --mode development --hot",
    "build": "webpack --mode production"
  },
  "author": "Souvik Ghosh",
  "license": "ISC",
  "dependencies": {
    "react": "^16.4.2",
    "react-dom": "^16.4.2"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  }
}

My webpack.config.js

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

module.export = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, '/build'),
    filename: 'index_bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/templates/index.html'
    })
  ]
};

My .babelrc

{
  "presets": ["env", "react"]
}

My directory structure

enter image description here

Expected behaviour

我启动了开发服务器 npm run dev . 期待看到我闪亮的新React js页面说"My first React Webpack project"(来自组件/components/App.js)

Actual Behavior

./src/index.js中的错误5:16模块解析失败:意外的令牌(5:16)您可能需要一个合适的加载器来处理此文件类型 . |从“./components/App”导入应用程序; | ReactDOM.render(,document.getElementById('root')); | //ReactDOM.render('Hello User',document.getElementById('root')); @ multi(webpack)-dev-server / client?http:// localhost:8080(webpack)/hot/dev-server.js ./src main2

如果需要,我可以通过git repo共享代码库 . 任何帮助是极大的赞赏 .

1回答

  • 1

    问题在于您的webpack配置文件中的拼写错误 .

    你有module.export不正确 . 它应该是module.exports

    工作实例

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: './src/index.js',
      output: {
        path: path.join(__dirname, '/build'),
        filename: 'index_bundle.js'
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader"
            }
          }
        ]
      },
      plugins: [
        new HtmlWebpackPlugin({
          template: './src/templates/index.html'
        })
      ]
    };
    

loading...

评论

暂时没有评论!