webpack bundle.js not found - 404错误

时间:2018-03-27 14:46:35

标签: javascript reactjs npm webpack

我正在尝试学习Webpack配置,并且在控制台中不断出现错误。好像我的webpack app.bundle.js还没有找到。

页面加载,我的html文件的内容显示,但不在app.bundle.js或hd文件中,在我的dist目录中,而不是直到我运行mpm build。

下面是webpack配置的代码和错误

// import node.js native path module
const path  = require('path');
let webpack = require('webpack');

//require HtmlWebPackPlugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const port = process.env.PORT || 3000;

//define constant for paths
const paths ={
 DIST: path.resolve(__dirname, 'dist'),
 SRC: path.resolve(__dirname, 'src'),
JS: path.resolve(__dirname, 'src/js')
};

console.log(paths.DIST);

//webpack configuration
module.exports ={
entry: path.join(paths.JS, 'index.js'),
output: {
    path: paths.DIST,
    filename: 'app.bundle.js'
},

//set starting point for server
devServer: {
    contentBase: paths.SRC,
    host:'localhost',
    port: port,
    historyApiFallback: true,
    open: true,
    hot:true
},

//set webpack to use plugins
plugins: [
    new HtmlWebpackPlugin({
        template: path.join(paths.SRC, 'index.html'),
    }),
    new ExtractTextPlugin('style.bundle.css'),
    new webpack.HotModuleReplacementPlugin()
],

//configure loaders
module: {
    rules: [

        //setup babel loader
        {
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: [
                'babel-loader',
            ],
        },

        //setup css loader
        {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract({
                use: 'css-loader',
            }),
        },

        {
            test: /\.(png|jpg|gif)$/,
            use: [
              'file-loader',
            ],
          },
    ],
},

//enable JS files without adding their extensions
resolve: {
    extensions: ['.js', '.jsx'],
},

};

以下是浏览器控制台上的错误

Loading failed for the <script> with source “http://localhost:3000/js/app.bundle.js”

Source map error: request failed with status 404 Resource URL: http://localhost:3000/app.bundle.js Source Map URL: sockjs.js.map

2 个答案:

答案 0 :(得分:1)

该帖子很旧,但希望这对将来的人有所帮助,因为我刚刚解决了一个类似的问题,请转到:

确保服务器根路径和输出路径对产生404错误的文件有意义。 具体来说,由“ contentBase:paths.SRC”设置的服务器根路径指向SRC文件夹,但是JS文件输出到path.DIST。当浏览器尝试访问这些文件时,它使用的URL指向错误的位置。通过将内容库更改为DIST或添加将覆盖内容库的publicPath: paths.DIST,来解决。

链接到contentBasepublicPath的引用。

答案 1 :(得分:0)

由于没有运行Webpack,同样的错误发生在我身上。

npx webpack

在与Webpack配置脚本相同的目录上运行它。