I have a Vue(hello-world) application using
webpack-dev-middleware and webpack-hot-middleware
[hrm] said it's connected in the console when I run the application
Then when I made some changes on my main.js, it thorws up
bundle rebuilding
bundle.js:1382 [HMR] bundle rebuilt in 95ms
bundle.js:2336 [HMR] Checking for updates on the server...
bundle.js:2409 [HMR] Updated modules:
bundle.js:2411 [HMR] - ./src/main.js
bundle.js:2416 [HMR] App is up to date.
Which is fine, but DOM does not reflect my changes and I have to manually reload the page in order to see them.
These are the code files I have right now:
// dev-server.js
...
app.use(middleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.path
}));
app.use(webpackHotMiddleware(compiler));
...
and here my webpack config:
module.exports = {
context: srcPath,
entry: ['webpack-hot-middleware/client', './main'],
resolve: {
extensions: ['.js', '.vue'],
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
output: {
path: distPath,
publicPath: distPath,
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
}
then I accept module hot changes on main.js:
import Vue from 'vue'
new Vue({
el: '#app',
data: {
message: "hello world!!"
}
})
if (module.hot) {
module.hot.accept();
}
I've struggled myself looking on forums and blog posts but seems I'm missing something, any ideas what could be the issue.
I am currently switching from Webpack 3 to 4 and I am facing the same problem as yours.
I think your dev-server.js has missing some codes. I know it is a bit late but I hope this could be an answer for someone who has been struggled few days like me.
For Webpack 4:
// dev-server.js
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat: 2000
});
compiler.hooks.compilation.tap('html-webpack-plugin-after-emit', () => {
hotMiddleware.publish({
action: 'reload'
});
});
For Webpack 3:
// dev-server.js
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat: 2000
});
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
});
});
I'd suggest blowing away all of the options to start with, and then incrementally add them as desired once you have basic functionality working. I think that your path option is actually the default anyway, and that heartbeat looks really long. (I'm also assuming the linebreak in your webpack entry config is a typo..)
You can see a working example of applying webpack-hot-middleware to an existing webpack-dev-middleware app (albeit React instead of Vue - and please ignore the CoffeeScript), that was done about a week ago. It's pretty bare, and is pretty similar to your setup, except with fewer options. (I'm also able to avoid having to touch module.hot myself, though I imagine that depends on what other libraries are in the mix.)
Related
I have a problem trying to make a build of a new Vue3.js + Vite.js application. Once my application is finished i made the npm run build action in order to generate the final deployment files.
Problem is that when I try to see the generated page, it only shows a white page.
Opening the inspection tool I can see how the main generated javascript files are like not being found by the static index.html:
Failed to load resource: net::ERR_FAILED index.7b66f7af.js:1
Ok. I found the solution searching a bit, and I see how this problem also occurred actually in Vue 2.
The only thing that you have to do for solvif is add base: './' in your vite.config.js, like this:
import {
defineConfig
} from 'vite'
import vue from '#vitejs/plugin-vue'
import vuetify from '#vuetify/vite-plugin'
const path = require('path')
export default defineConfig({
plugins: [
vue(),
vuetify({
autoImport: true,
}),
],
define: {
'process.env': {}
},
resolve: {
alias: {
'#': path.resolve(__dirname, 'src'),
},
},
base: './',
})
Hope it helps you all!
I had this problem also, and found a solution:
It looks like the awnser given by #javi But it's different. I found out that the situation changes when you deploy your application.
In vite config there is a setting called 'base' filled in like: base: mode === 'production' ? '/nameExample/' : '/', this will put the output of your project on the endpoint : 'nameExample'. If you go in production this fails and shows a blank page, and you need to changes this nameExample to '/' to show the projectbuild online. But than it shows a blank page in development because it mismatches the name of the project. Hope this will help you.
So I have a vue-js application and today I started using prerender-spa-plugin to generate some static pages for better SEO. When I run npm run build, everything works perfect, no errors. Now when I want to run the development server with npm run serve, I get the following error (only a part of it)
error in ./src/main.js
Module build failed (from ./node_modules/babel-
loader/lib/index.js):
Error: .plugins[0] must include an object
at assertPluginItem (/Users/user/Desktop/app/node_modules/#babel/core/lib/config/validation/option-assertions.js:231:13)
So I guess the problem has to do with the babel plugin loader. So I commended every part of my code using prerender-spa-plugin, but I still get the same error. I hope someone can point me to the right direction.
My babel.config.js
const removeConsolePlugin = []
if(process.env.NODE_ENV === 'production') {
removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
presets: [
'#vue/app'
],
plugins: [removeConsolePlugin]
}
My vue.config.js
const path = require('path');
const PrerenderSpaPlugin = require('prerender-spa-plugin');
const productionPlugins = [
new PrerenderSpaPlugin({
staticDir: path.join(__dirname, 'dist'),
routes: ['/', '/documentation'],
renderer: new PrerenderSpaPlugin.PuppeteerRenderer({
// We need to inject a value so we're able to
// detect if the page is currently pre-rendered.
inject: {},
// Our view component is rendered after the API
// request has fetched all the necessary data,
// so we create a snapshot of the page after the
// `data-view` attribute exists in the DOM.
//renderAfterElementExists: '[data-view]',
}),
}),
];
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
config.plugins.push(...productionPlugins);
}
}
}
i'm trying to use web workers in my web app but i'm having a hard time. Adding a new entry to the webpack.config.js does not work.
so, I'm trying to use the npm package called worker-loader but there is no proper example on how to use it. All of my attempts to use it has failed. Can you guys please show me a simple example on how to use it.
import Worker from "worker-loader!./Worker.js";
const myworker = new Worker();
myworker.postMessage(songs);
myworker.onmessage = function(Data) {
//do something
}
my webpack.config.js file is like this with
entry: __dirname + "/js/index.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
{
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
]
}
}
My server tells me the following:
"GET /279b1e1fcb403131377a.worker.js HTTP/1.1" 404
Since my 279b1e1fcb403131377a.worker.js is inside /dist its giving me 404 error. How can i make the request to go inside /dist.
There are plenty of examples given on the official Github page:
https://github.com/webpack-contrib/worker-loader
That should easily get you going.
I am trying to port my Aurelia application from System.js + JSPM to Webpack. The app has multiple entry htmls: index.html, index2.html.
As I am new to Webpack, I started with aurelia skeletons using easy-webpack, and tried to add my application specific codes gradually.
For the most basic case with single entry index.html the skeleton worked quite well. Also I added my local modules as node_modules and used the same in the app.
However, I am not able to setup the configurations properly for multiple entry htmls. This is what my webpack.config.js (showing the parts where it is modified) looks like:
const baseConfig = {
entry: {
'app': [/* this is filled by the aurelia-webpack-plugin */],
'aurelia-bootstrap': coreBundles.bootstrap,
'aurelia': coreBundles.aurelia.filter(pkg => coreBundles.bootstrap.indexOf(pkg) === -1),
'some-common-script': path.resolve('src/some-common-script.js'),
'index1-script': path.resolve('src/index1-script'), //needed exclusively in index.html
'index2-script': path.resolve('src/index2-script') //needed exclusively in index2.html
}, ...
};
switch (ENV) {
...
default:
case 'development':
process.env.NODE_ENV = 'development';
config = generateConfig(
baseConfig,
...
require('#easy-webpack/config-common-chunks-simple')
({ appChunkName: 'app', firstChunk: 'aurelia-bootstrap' }),
require('#easy-webpack/config-generate-index-html')
({ minify: false, overrideOptions: { excludeChunks: ["index2-script"] } }),
require('#easy-webpack/config-generate-index-html')
({
minify: false, overrideOptions: {
chunks: ['some-common-script', 'index2-script'],
filename: 'index2.html',
template: 'index2.html',
}
}),...
);
break;
}
module.exports = config;
The problems are as follows:
If I exclude index2-script from the default config-generate-index-html, then the order in which the scripts are added in index.html becomes app.bundle.js, aurelia-bootstrap.bundle.js, ..., instead of aurelia-bootstrap.bundle.js, app.bundle.js, ..., which causes Uncaught ReferenceError: webpackJsonp is not defined....
As per my understanding that error is caused as easy-webpack/config-common-chunks-simple (wrapper around webpack.optimize.CommonsChunkPlugin) packed the initial, and common codes into aurelia-bootstrap.bundle.js ("bootstrap" chunk). Thus, I tried without require('#easy-webpack/config-common-chunks-simple')({ appChunkName: 'app', firstChunk: 'aurelia-bootstrap' }) as well, but instead got
Uncaught TypeError: Reflect.getOwnMetadata is not a function from aurelia-metadata.js, and
Uncaught TypeError: Cannot read property 'call' of undefined from webpack:///webpack/bootstrap <hash>, which seems to be raised because of a module is not found.
I am completely confused about what I should I try next. Please suggest.
Heres my config:
devServer: {
contentBase: '/web/dist/',
hot: true,
stats: {colors: true},
inline: true
}
And here's the gulp task im running:
gulp.task('build', ['clean', 'styles', 'bower', 'media', 'data', 'homepage'], function(done) {
es6promise.polyfill();
console.log('STARTING DEV SERVER...');
server = new WebpackDevServer(webpack(webpackDevConfig), webpackDevConfig.devServer);
server.listen(8080, '0.0.0.0', function (err, stats) {
if (err) {
throw new gutil.PluginError("webpack-dev-server", err);
}
console.log('DEV SERVER STARTED');
done();
});
});
Everything works as expected except the hot loading (no refresh or change when I make changes to files). What am I doing wrong here?
You need to add <script src="http://localhost:8080/webpack-dev-server.js"></script> to your index.html It is not added when you use the API
"Notice that webpack configuration is not passed to WebpackDevServer API, thus devServer option in webpack configuration is not used in this case. Also, there is no inline mode for WebpackDevServer API. <script src="http://localhost:8080/webpack-dev-server.js"></script> should be inserted to HTML page manually."
(http://webpack.github.io/docs/webpack-dev-server.html)
maybe you also need to add 'webpack/hot/dev-server' as an entrypoint to your webpack config
be sure to set
webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
in the webpackConfig as well
If you are using redux can try this.
For some random reason redux-devtools was not allowing hot reload for me. Try removing it from root component and redux compose config.
Note: Use redux devtool browser extension with this config in your store configuration: window.devToolsExtension ? window.devToolsExtension() : f => f
Also, must read: https://medium.com/#rajaraodv/webpacks-hmr-react-hot-loader-the-missing-manual-232336dc0d96#.ejpsmve8f
Or try hot reload 3:
example: https://github.com/gaearon/redux-devtools/commit/64f58b7010a1b2a71ad16716eb37ac1031f93915