开发者问题收集

Webpack 无法在简单项目中使用 npm start

2019-05-26
1307

这是我的包文件和 webpack 配置。我正在学习这项技术,但这不起作用。我在一个空白画布项目中收到以下错误。我做错了什么吗?

非常感谢,

错误消息

ERROR in ./src/index.js 6:16
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
| import App from './App';
| 
> ReactDOM.render(<App />, document.getElementById('root'));

package.json

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --mode development --watch",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^2.1.1",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  }
}

webpack.config.js

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

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};

App.js

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div>
                <h1>hello</h1>
            </div>
        )
    }
}

我现在有以下 webpack.config.js

更新 - 完整文件

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

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};

进行此更改后,在运行 npm install 后,运行 npm start 时出现以下错误

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module has an unknown property 'loaders'. These properties are valid:
   object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPrese
nce?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, w
rappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
   -> Options affecting the normal modules (`NormalModuleFactory`).
 - configuration.resolve.extensions[0] should be an non-empty string.
   -> A non-empty string
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `webpack --mode development --watch`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

更新 2

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

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, './dist'),
    filename: 'index_bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
            loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()]
};

此版本的

文件

[./src/index.js] 3.16 KiB {main} [not cacheable] [built] [failed] [1 error]

ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'
 babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:613:15)

2个回答

将其添加到您的 webpack 中 ...您的 webpack 中的代码...

,resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015']
        }
      }
    ]
  }

在您的文件夹中尝试 npm install ,然后再次使用 npm start

evilGenius
2019-05-26

首先,您的属性

module:{ loaders

不正确,应该是 modules->rules 。其次,您的文件夹中没有任何 JSX,您有 App.js,因此您的规则应该对其进行测试并为其加载适当的加载器,即 babel-loader,其预设设置为 react

 module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }

要告诉 babel 使用 react 作为其预设,您可以在上述配置中指定或创建一个包含以下内容的 .babelrc 文件。

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

之后,您就可以开始了

Avij
2019-05-27