Webpack错误:无法解析'./src'

4

我是webpack的新手。我正在学习react并使用webpack为其构建环境。

我有一个webpack-config.js文件。

var path = require('path');


module.exports = {
    mode: 'production',
    entry: './script.js',
    output: 
    {
        path: path.resolve(__dirname, 'src'),
        filename: 'transpiled.js'
    },
    module: 
    {
        loaders: [
        {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query:
            {
                presets: ['es2015','react']
            }
        }
        ]
    }
}

和 script.js

    import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <h1>Hello world</h1>    
    document.getElementByIdName('first')
);

和 index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="first"></div>
    <script src="transpiled.js"></script>
</body>
</html>

在 Pakage.json 文件中我已经写了。
"scripts": {
    "it": "webpack-dev-server --hot" 
  },

但是当我使用"npm run it"运行npm时,它向我显示以下错误:

配置警告 'mode'选项未设置。将'mode'选项设置为'development'或'production'以启用此环境的默认值。 多个错误 -dev-derver/client?http://localhost:8080 webpack/hot/dev-server ./src 找不到模块:错误:无法解析'D:\ React Js \ LearnReact'中的'./src' @multi -dev-derver/client?http://localhost:8080 webpack/hot/dev-server ./src i ?wdm?:编译失败。

请帮帮我,我真的卡住了,想知道解决方案。


你创建了一个 src 文件夹吗? - brk
你有加载webpack配置文件吗?如果我没记错的话,你必须在npm脚本中指定它或使用默认名称webpack.config.js。请查看文档https://webpack.js.org/configuration/。 - Joshua
1个回答

4
您需要将--config选项添加到webpack-dev-server中:

webpack-dev-server --config path/to/webpack.config.js

还要在基础配置中设置您的模式为development,当进行生产构建时,可以稍后覆盖它。

还要确保您的./script.js文件位于项目的根目录中,即与您的package.json文件旁边,因为此文件路径相对于npm脚本执行。

基于这个配置-->path: path.resolve(__dirname, 'src'),所有构建的资产都将以src文件夹的形式出现在项目的根目录中,假设您的webpack.config.js文件在那里(此路径相对于您的配置文件)。实际文件夹只会在production中生成,在development中,资产存储在内存中。

您可能还希望设置一个publicPath

output: {
  ...
  publicPath: '/'
}

我建议您使用html-webpack-plugin,因为它可以为您解析正确的js文件路径。

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

...
plugins: [
  new HtmlWebpackPlugin({
    filename: 'index.html', // name of file that will be outputted to 'src' when built
    template: // path to your html file relative to config
    inject: true
  })
]

那么您就不必包含脚本的路径,因此您的HTML文件会像这样:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="first"></div>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接