Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dev-server not bundling #24

Closed
mlrawlings opened this issue May 28, 2014 · 36 comments
Closed

dev-server not bundling #24

mlrawlings opened this issue May 28, 2014 · 36 comments

Comments

@mlrawlings
Copy link
Contributor

There's a good chance this is user error, but I cannot get webpack-dev-server to update my bundles correctly.

I've installed both webpack and webpack-dev-server globally using npm. I can bundle perfectly fine with the webpack command, but the webpack-dev-server is not working correctly. The terminal output indicates that the bundle was successful but nothing is written to the file system. The live reload and app status work as intended, but upon reload it serves the contents of the file system which are out of date.

Here's a simple example in which I'm having trouble:

index.html

<html>
    <body>
        <script src="/bin/init.js"></script>
    </body>
</html>

webpack.config.js

module.exports = {
    entry: "./src/init.js",
    output: {
        path: "bin/",
        filename: "init.js",
    },
    devtool: "sourcemap",
    debug: true
};

src/init.js

console.clear();
console.log('initialized.');

webpack-dev-server output. This does not write anything to the file system.

http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from C:\Users\Owner\Workspace\webpack-test
Hash: 801e0272a219e10a6229
Version: webpack 1.2.0-beta6
Time: 108ms
      Asset  Size  Chunks             Chunk Names
    init.js  1611       0  [emitted]  main
init.js.map  1353       0  [emitted]  main
chunk    {0} init.js, init.js.map (main) 44 [rendered]
    [0] ./src/init.js 44 {0} [built]
webpack: bundle is now VALID.

webpack output. This does write the bundle correctly.

Hash: 801e0272a219e10a6229
Version: webpack 1.2.0-beta6
Time: 89ms
      Asset  Size  Chunks             Chunk Names
    init.js  1611       0  [emitted]  main
init.js.map  1353       0  [emitted]  main
   [0] ./src/init.js 44 {0} [built]

I'm running Windows 8.1, and I've tried using older versions (1.2.7 and 1.2.1) of webpack-dev-server. Any help would be appreciated!

@sokra
Copy link
Member

sokra commented May 28, 2014

The webpack-dev-server doesn't write to disk. It serves the result from memory.

The line webpack result is served from / indicates that your bundle is served from /init.js, but your html expects it to be at /bin/init.js. You need to tell the webpack-dev-server where your assets should be served by setting output.publicPath. In your case set it to output.publicPath: "/bin/" (this is also required for Code Splitting).

@mlrawlings
Copy link
Contributor Author

Thanks for clearing that up!

@KyleAMathews
Copy link

It'd be nice if we could configure webpack-dev-server to also write to disk. It's not that big of performance hit and I've run into a few situations where this would simplify things.

@sompylasar
Copy link

refs #62

@SamEureka
Copy link

+1 thanks @sokra

@WesleyBatista
Copy link

So the "watch" functionality is still accomplished only by the webpack.

We still need to run two commands to get the "live-reload" functionality?

webpack-dev-server --hot and webpack

Is that right?

@keepitreal
Copy link

keepitreal commented May 5, 2016

@WesleyBatista No --hot takes care of that for you. The confusion is that, with other module bundlers, it will bundle and then write a file to your project directory. Webpack is able to accomplish live-reloading and hot module replacement by just writing to memory on the Express server that webpack-dev-server spins up. So you may need to adjust how you reference your app's .js file in your index.html depending on how you set your public path in your webpack config file.

csanyiarpad added a commit to UltimateHackingKeyboard/agent that referenced this issue Aug 1, 2016
The issue was that the webpack-dev-server seemed to serve the old files
instead of the newly bundled ones.
The explanation of the solution can be found here:
webpack/webpack-dev-server#24 (comment)
@abbymrs
Copy link

abbymrs commented Oct 25, 2016

@sokra, i have the same problem, run webpack-dev-server, no output files, but when i run webpack, it works,i dont know where i was wrong. below is my webpack.config.js file:

const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin');

let src = {
    app: 'public/js/*.js',
    vendor: [
        'public/vendor/*.js',
        'node_modules/angular/angular.js',
        'node_modules/angular-resource/angular-resource.js',
        'node_modules/angular-ui-router/release/angular-ui-router.js',
        'node_modules/ngstorage/ngStorage.js',
    ],
    html: 'public/views/index.html'
}
module.exports = {
    entries: {
        index: src.app,
        vendor: src.vendor
    },
    output: {
        path: path.join(__dirname, 'build'),
        publicPath: path.join(__dirname, 'build'),
        filename: '[name].bundle.js',
        sourceMapFilename: '[name].map',
        chunkFilename: '[id].chunk.js',
        lazy: true
    },
    devtool: 'cheap-module-source-map',
    debug:true,
    module: {
        rules: [{
            test: /\.css$/,
            loaders: ['to-string-loader', 'css-loader']
        }, {
            test: /\.html$/,
            loader: 'raw-loader'
        }, {
            test: /\.js$/,
            loader: 'script-loader',
            exclude: ['./node_modules/**/*.js']
        }, {
            test: require.resolve("jquery"),
            loader: "imports?jQuery=jquery,$=jquery,this=>window,require=>false"
        }]
    },
    plugins: [
        new CommonsChunkPlugin({
            name: 'vendor'
        }),
        new CopyWebpackPlugin([{
            from: './public',
            to: 'assets'
        }]),
        new HtmlWebpackPlugin({
            template: src.html,
            chunksSortMode: 'dependency',
            inject: 'head'
        }),
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery'
        }),
        new HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: ['', '.js', '.json', '.css'],
        alias: {
            jquery: 'jquery/src/jquery'
        }
    },
    devServer: {
        port: 5000,
        host: 'localhost',
        historyApiFallback: true,
        watchOptions: {
            aggregateTimeout: 300,
            poll: 1000
        },
        outputPath: path.join(__dirname, 'build'),
        proxy: {
            '/api/*': 'http://localhost:8000'
        }
    },
    node: {
        global: true,
        crypto: 'empty',
        process: true,
        module: false,
        clearImmediate: false,
        setImmediate: false
    }
}

@SpaceK33z
Copy link
Member

@abbymrs, as stated above:

The webpack-dev-server doesn't write to disk. It serves the result from memory.

If you still have problems, I'd suggest to create a StackOverflow question. You have a better chance to get help there.

@abbymrs
Copy link

abbymrs commented Oct 25, 2016

@SpaceK33z,
Do you mean I need to run webpack to build files firstly, then run webpack-dev-server?

@SpaceK33z
Copy link
Member

No, but you shouldn't expect that it writes them to disk. The server in webpack-dev-server exposes these files. In your case, the files should be available in http://localhost:5000. Depending on output.publicPath , the directory of where these files are may differ. I suggest to change your output.publicPath to /build/.

@abbymrs
Copy link

abbymrs commented Oct 25, 2016

I got your ideas, thanks.

@daslicht
Copy link

I also have the same issue:

    output: {
        filename: "bundle.js",
        path: "./dist",
        publicPath: "./dist"
    },
   <!-- Main -->
        <script src="./dist/bundle.js"></script>

But I still get ./dist/bundle.js is undefined when using webpack-dev-server

I am using :

    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"

what am I missing please?

@daslicht
Copy link

I just tried tis , which seam to work :

    output: {
        filename: "./dist/bundle.js",
    },

@reduxdj
Copy link

reduxdj commented Jan 25, 2017

This definitely seems like an awful bug... no error when there's no output, why is webpack such a hairpuller?

@jcrben
Copy link

jcrben commented Apr 5, 2017

I know this was closed 2014, but it seems that people (including myself) still run into similar issues. Maybe errors or documentation could be improved. Webpack should by default put the user on the path to ensuring that webpack-dev-server and webpack builds are in sync.

@dimwell-git
Copy link

Still in 2017 I had same issues.

If people still write about an issues, then probably the issues does exist and a proper solution is needed...

Temporary solution:

  1. run both: webpack-dev-server and webpack with --watch
    OR
  2. check comment: daslicht commented on Nov 14, 2016 which advice ->
    output: {
    filename: "./dist/bundle.js",
    },

@charusat09
Copy link

This is very poor and much challenging for a new developer. I just lost much time for resolving this issue. I tried every solution available on the web and then I found it's core bug of webpack-dev-server. Needs to be fixed or mention in documentation until you resolve this.

run both: webpack-dev-server and webpack with --watch works for me. Thanks @dimwell-git

@nukeop
Copy link

nukeop commented May 29, 2017

Yep, I'm also having issues with this.
I managed to get webpack-dev-server to output files into my static directory but hmr request files with different names and runs into 404s.

@d4rekanguok
Copy link

d4rekanguok commented Jun 5, 2017

The answer was given twice above, if your bundle file is output to ./bin and you point your html to that, in your webpack.config.js set publicPath to /bin/:

output: {
    // the URL of your output.path from the view of the HTML page.
    publicPath: '/bin/'
}

More at the doc: https://webpack.js.org/configuration/output/#output-publicpath

@golddranks
Copy link

golddranks commented Jun 16, 2017

I was suffering of the same problem, and found the earlier answers – although correct – confusing.

Here's how I resolved it: (Tried to write from the viewpoint of the things I was confused about.)
First of all, there seems to be two settings for publicPath: output.publicPath and devServer.publicPath. Both should be set to the path that is seen in the BROWSER, after the domain name, so no file system paths. Also, they must end with /. Confusingly, "public" there doesn't mean a public path in the sense that the server exposes static files publicly – that's the contentBase setting. If it helps someone, please think of publicPath as a bundleRoute instead.

output.path = filesystem path where the bundled stuff is saved
output.publicPath = URL path where the stuff are expected to reside when online (the path after the domain name)
devServer.contentBase = filesystem path where the static content is served from
devServer.publicPath = URL route where the bundled stuff is served from

@pmunin
Copy link

pmunin commented Aug 18, 2017

I spent half a day for that problem and I finally figured it all out. 🎊 🎆 So if it still does not work for you, here we go.

Basically all you need to do if it does not work is to look carefully the output of your webpack-dev-server, especially the colored words. E.g. in my case it was the following (colored words are bold):

Executing task: npm run webpack-dev-server <

webpack-dev-server c:\Users\work\Documents\MyProject
webpack-dev-server --config .webpack/config.js

Project is running at http://localhost:8080/
webpack output is served from /dist/
ts-loader: Using [email protected] and c:\Users\work\Documents\MyProject\tsconfig.json
webpack: wait until bundle finished: /dist/MyEntryModule.bundle.js
Hash: d4f3d16c19e027f46c7f
Version: webpack 3.5.5
Time: 4842ms
Asset Size Chunks Chunk Names
MyEntryModule.bundle.js 418 kB 0 [emitted] [big] MyEntryModule
[6] ./src/_refs.ts 3.94 kB {0} [built]
.......

So what I see here:

  1. Project is running at http://localhost:8080/
  2. webpack output is served from /dist/
  3. the name of compiled bundle: MyEntryModule.bundle.js 418 kB

So if you just concatenate those (trimming trailing slash from component #1), you will get CASE SENSITIVE url that will be successfully served by webpack-dev-server:
http://localhost:8080/dist/MyEntryModule.bundle.js. However it will not write it to disk, but will serve it as a in-memory virtual file system, overriding your physical file system.

Too many config parameters may impact the eventual URL and this is what causes so much confusion. The simplest config would be something like this:

    entry: { MyEntryModule: "./src/index.ts" },
    output: {
        filename: "[name].bundle.js", //<- defines URL component #3 above
        //path: path.resolve("dist"), //<- this defines the path of output if you do regular build, but completely IGNORED by devserver's url, so it does not have to be here to make devserver work
        //publicPath:"/dist/", //<-it can be specified either here or in devServer, which overrides it anyways
   },
   devServer:{
        publicPath:"/dist/"  //<- this defines URL component #2 above
   }

Big part of confusion that webpack-dev-server serves case sensitive URLs, so if your HTML's script tag asks for /dist/mymodule.bundle.js, and in your webpack.config your entry name is MyModule, then your browser will get 404.

@BenSpace48
Copy link

Still seems to be an issue in 2018.

All my files are currently in the root directory and the server does not update so for me it is not related to output.publicPath or devServer.publicPath.

The only fix that works for me is to run webpack --watch and webpack-dev-server at the same time.

@m1520n
Copy link

m1520n commented Jan 17, 2018

@windmaomao
Copy link

why not just webpack --watch and then do whatever server you are doing. It's just too much from the very beginning.

@dgroh
Copy link

dgroh commented Mar 15, 2018

I would suggest a much simpler approach:

webpack --watch with browserSync if you want the browser to reload after file changes

@nukeop
Copy link

nukeop commented Mar 15, 2018

Installing a huge third party dependency is a bad solution to a problem with functionality that should technically already be working.

@dgroh
Copy link

dgroh commented Mar 15, 2018

is it's not working tho...and browserSync has been a common approach for a long time, if you used to work with gulp or grunt that was the way to sync the browser

@dgroh
Copy link

dgroh commented Mar 15, 2018

I got it to work by the way, is important to use the HtmlWebpackPlugin, that what I was missing

module.exports = merge(baseConfig, {
  devtool: "inline-source-map",
  output: {
    path: path.resolve(__dirname, "../dist"),
  },
  plugins: [
    new HtmlWebpackPlugin({ template: "index.html" })
  ]
});

@nukeop
Copy link

nukeop commented Mar 15, 2018

I think that's only coincidental, I got it working some time ago without this plugin.

@davidshare
Copy link

davidshare commented Mar 30, 2018

Hi, I am having issues with setting up webpack. Everything seems to be okay, but the bundle file is not being generated, neither is the HTML file. Here is my webpack.config.js. I'm using webpack 4
`
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const port = process.env.PORT || 3000;

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

const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html"
});

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

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

		{
			test: /\.css$/,
			use: [
				{
					loader: "style-loader"
				},

				{
					loader: "css-loader",
					options:{
						modules: true,
						importLoaders: 1,
						localIndentName: "[name]_[local]_[hash:base64]",
						sourceMap: true,
						minimize: true,
						camelCase:true
					}
				}
					
			]
		}
	]
},

plugins: [htmlPlugin],

devServer: {
	publicPath: paths.DIST,
	host: 'localhost',
	port: port,
	historyApiFallback: true,
	open:true,
	hot: true
}

};
`

@disler
Copy link

disler commented Apr 5, 2018

@golddranks This explanation helped a ton thank you

@reyou
Copy link

reyou commented Apr 22, 2018

To run dev-server and --watch at the same time:

npm i --save-dev parallelshell
https://github.com/darkguy2008/parallelshell

"scripts": {  
    "watch": "webpack --watch",
    "server":
      "webpack-dev-server --config ./webpack.config.js --mode development",
    "start":
      "parallelshell \"webpack --watch\" \"webpack-dev-server --config ./webpack.config.js --mode development\""
  },

Then npm run start

Verify both dist folder created and http://localhost:8080/ works at the same time.

@daniilc-magnumwm
Copy link

daniilc-magnumwm commented Jul 5, 2018

It is quite weird, but all I have to do is to change the the output in the following way.
I have just commented the path and publicPath lines and specified the whole path in a filename

  output: {
    //path: path.resolve(__dirname, './dist'),
    //publicPath: './dist/',
    filename: './dist/build.js'
  },

npm -v
6.1.0

node -v
v10.5.0

@nukeop
Copy link

nukeop commented Jul 5, 2018

What if you want to output more than one file?

@ismail2009
Copy link

ismail2009 commented Jul 24, 2018

const path = require('path');

module.exports = {
  entry: './src/views/index.js',
  output: {
    path: path.join(__dirname, 'public/'),
    filename: 'bundle.js',
    publicPath: '/public/'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  stats: {
    colors: true,
    reasons: true,
    chunks: true
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: 'babel-loader'
    }, {
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    }, {
      test: /\.(png|jpg|gif|ico)$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]',
          context: path.join(__dirname, 'src/views/')
        }
      }]
    }]
  },
  devtool: 'cheap-eval-source-map',
  devServer: { 
    publicPath: '/public/',
    historyApiFallback: true
   }
};
"dev:start": "webpack-dev-server --mode development " 

if I remove the bundle and start webpack-dev-server the bundle doesn't appear but the compiler work correctly and the server work without bundle How is that and why I can't find the bundle but every thing is work

webpack-dev-server --mode development 
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /public/
ℹ 「wds」: 404s will fallback to /index.html
ℹ 「wdm」: Hash: 8de3f883d29c1e0cb498
Version: webpack 4.16.1
Time: 2665ms
Built at: 07/24/2018 8:38:14 PM
             Asset      Size  Chunks             Chunk Names
assets/Portgas.jpg   122 KiB          [emitted]  
         bundle.js  3.22 MiB    main  [emitted]  main
Entrypoint main = bundle.js
[./node_modules/loglevel/lib/loglevel.js] 7.68 KiB {main} [built]
[./node_modules/react-dom/index.js] 1.33 KiB {main} [built]
[./node_modules/react/index.js] 190 bytes {main} [built]
[./node_modules/strip-ansi/index.js] 161 bytes {main} [built]
[./node_modules/url/url.js] 22.8 KiB {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 7.78 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.58 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.05 KiB {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./node_modules/webpack/hot/emitter.js] (webpack)/hot/emitter.js 75 bytes {main} [built]
[./src/views/components/App/index.js] 911 bytes {main} [built]
[./src/views/components/Home/index.js] 324 bytes {main} [built]
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./src/views/index.js 40 bytes {main} [built]
[./src/views/index.css] 1.06 KiB {main} [built]
[./src/views/index.js] 203 bytes {main} [built]
    + 119 hidden modules
ℹ 「wdm」: Compiled successfully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests