入口模块未找到:错误:无法解析'./src/index.js'。

25
我正在安装一个React启动应用程序,添加了Webpack,但它显示“Can't resolve './src/index.js'”。 浏览器显示 My app gives this look 我的文件路径和Package.json内容 enter image description here Webpack.config.js 内容
 var debug = process.env.NODE_ENV !== "production";
    var webpack = require('webpack');
    var path = require('path');

    module.exports = {
        context: path.join(__dirname, "public"),
    devtool: debug ? "inline-sourcemap" : false,
    entry: "./src/index.js",
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2016', 'stage-0'],
                    plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
                }
            }
        ]
    },
    output: {
        path: __dirname + "/public/",
        filename: "build.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
};
8个回答

22

你的基础URL是path.join(__dirname, "public"),而你的入口是./src/index.js。Webpack试图在public目录中找到./src/index.js文件;显然该文件不存在。你应该将entry修改为../src/index.js


感谢@kermit ERROR in ./src/index.js 模块构建失败:错误:相对于目录"C:\\Users\\ashik\\Desktop"找不到预设"es2016"但我收到了新的错误。 - MD Ashik
在我的情况下,使用..解决了类似的导入错误问题,谢谢! - franciscorode

10

我发现解决这个问题的另一种方法是使用path.resolve()

const path = require('path');
module.exports = {
    mode: "production",
    entry: path.resolve(__dirname, 'src') + 'path/to/your/file.js',
    output: {
        /*Webpack producing results*/
        path: path.resolve(__dirname, "../src/dist"),
        filename: "app-bundle.js"
    }
}

这将确保Webpack在src目录中寻找入口点。
顺便说一下,这是默认入口点。您也可以将此入口点更改为适合您的位置。只需将src目录替换为您想要使用的其他目录即可。

2
我的webpack.config.js文件名为Webpack.config.js,而新的命令行界面是区分大小写的,因此找不到该文件。

2

默认情况下,Webpack不会查找.js文件。您可以配置resolve.extensions以查找.ts文件。别忘了添加默认值,否则大多数模块将会出错,因为它们依赖于自动使用.js扩展名的事实。

resolve: {
    extensions: ['.js', '.json']
}

1
我曾遇到相同的问题,发现是因为之前使用 npm install -g create-react-app 全局安装了 create-react-app。由于现在不应该全局安装 create-react-app,所以我需要先使用 npm uninstall -g create-react-app 卸载它,然后在我的项目目录中使用 npx create-react-app *my-app-name* 安装它。

1
入口路径是相对于上下文的。当你希望查找路径为 /src 时,它会在 public/src/ 中查找文件。看一下你的 webpack.config.js 的其余部分,似乎你根本不需要上下文行。

https://webpack.js.org/configuration/entry-context/


0
我的解决方案是将App.js文件放在src文件夹内的components文件夹中,并将index.js文件保留在src文件夹中。

0

我曾经遇到过同样的问题。解决方案其实很简单,就是我忘记在我的webpack.prod.js文件中添加module.exports

所以正确的写法应该是:

merge(common, {
...
});

使用

module.exports = merge(common, {
...
});

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