Vue CLI 3 prerender-spa-plugin - javascript

I've tried to prerender the routes of my SPA with the npm package prerender-spa-plugin with Vue CLI 3, and I get a decent output as seen here after running "npm run build":
The output in the index.html is an error:
<html>
<head>
</head>
<body>Html Webpack Plugin:
<pre> ReferenceError: BASE_URL is not defined
- index.html:96
C:/Users/Fred/v2/public/index.html:96:11
- index.html:99 0971.module.exports
C:/Users/Fred/v2/public/index.html:99:3
- index.js:284 Promise.resolve.then
[v2]/[html-webpack-plugin]/index.js:284:18
</pre>
</body>
</html>
My vue.config.js is this:
const path = require('path');
const PrerenderSPAPlugin = require('prerender-spa-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
inject: false
}),
new PrerenderSPAPlugin({
staticDir: path.join(__dirname, './dist'),
routes: ['/', '/om-guldbaek', '/om/:id', '/aktiviteter', '/aktivitet/:id', '/foreninger', '/forening/:id', '/begivenheder', '/begivenhed/:id', '/gdpr', '/institutioner', '/institution/:id', '/login', '/nyheder', '/nyhed/:id', '/kontakt', '/registreringer'],
})
],
},
};
When I run "npm run build" in VSCode, it keeps returning "Building for production..." without anything happening. Anyone know about this issue?

Alright I found the issue. In the index.html I had the line:
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
So now it's fixed

Related

webpack module function not found

I have a simple project with a few html files in root folder and a few javascript modules in scripts directory.
I want to start using webpack now because I want minification and to start using environments. Everything was working before I started using webpack.
I read documentation for Webpack 5 but could not find anything that solves my problem. So I came up with this webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
entry: {
lib: "./scripts/lib.js"
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
devServer: {
contentBase: "./dist",
inline: true, //Enable watch and live reload
host: "localhost",
port: 8080,
stats: "errors-only",
https: false
},
plugins: [
new HtmlWebpackPlugin({
filename: "index.html",
template: "index.html",
hash: true
})
],
module: {
rules: [
{
test: /\.html$/i,
loader: 'html-loader',
},
],
},
};
My index.html imports and uses module functions like this:
<script type="module">
import * as lib from "./scripts/lib.js";
window.lib = lib;
</script>
<body onload="lib.myFn()">
</body>
But after running this webpack (using webpack serve) I am getting "is not a function" or "module not found" errors.
How can I compile and run my existing project with webpack without making any changes in my directory structure and fix this error so I can start using functions in lib.js in my index.html? Thanks.

How to tell web pack to use external js file url without freezing in in bundle?

There is a simple task:
I want to try making a Google Chromecast receiver app (which is SPA). Google Chromecast SDK (cast SDK) requires their framework to be on external url. Also this framework creates global cast object.
What is the correct way of creating this webpack application?
The targets I want to achieve:
Build index.html with HtmlWebpackPlugin
Develop using import this framework (import cast from ???)
Avoid bundling it (probably using externals)?
Ensure cast object created by this js file is global (ProvidePlugin?)
Add <script src="http://cdn....js"></script> into HTML created by HtmlWebpackPlugin
For now I am trying to setup simple app, and I got stuck on last step - adding <script> tag to output html, but I'm sure that there are mistakes I've done on prev steps.
Could you help guiding me through this process?
My current webpack.config.js is:
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
module: {
rules: [
{ test: /\.svg$/, use: 'svg-inline-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
{ test: /\.(js)$/, use: 'babel-loader' }
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
scriptLoading: 'defer',
hash: true,
}) ,
new webpack.ProvidePlugin({
cast: path.resolve(path.join(__dirname, 'src/cast_receiver_framework'))
})
],
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devServer: {
compress: false,
disableHostCheck: true
},
externalsType: 'script',
externals: {
cast_receiver_framework: ['//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js', 'cast']
}
}
To solve your last step you can use the template param of HtmlWebpackPlugin to customize your template.
By default HtmlWebpackPlugin will inject bundled modules at the end of the <body>.
Check the documentation if you need further customization.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Whatever else you might need -->
</head>
<body>
<div id="your-mount-point-id"></div>
<script src="http://cdn....js"></script>
</body>
</html>
webpack.config.js
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "path/to/index.html"),
scriptLoading: 'defer',
hash: true,
})
],

Vue CLI 3 prerender-spa-plugin displaying blank pages and same index.html

I've run "npm run build" and the output of my file folders are the following:
Then if I dig in deeper, all the page folders have an index.html file containing:
The code for my vue.config.js and the prerender-spa-plugin is:
const path = require('path');
const PrerenderSPAPlugin = require('prerender-spa-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
inject: false
}),
new PrerenderSPAPlugin({
staticDir: path.join(__dirname, './dist'),
routes: ['/', '/om-guldbaek', '/aktiviteter', '/foreninger', '/begivenheder', '/gdpr', '/institutioner', '/login', '/nyheder', '/kontakt', '/registreringer'],
})
],
},
};
When I publish the website to Netlify with GitHub I get a blank website with no errors in the console. If it helps you can go to: https://guldbaekby.netlify.com
Any help is appreciated, thanks

Cannot GET / with webpack-dev-server

How come I am getting Cannot GET / in my browser? I think it is because my webpack-dev-server does not have a route to GET the bundled files.
devServer/server.js
import config from '../../webpack.config';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import open from 'open';
// template! https://github.com/webpack/webpack-dev-server/blob/master/examples/node-api-simple/server.js
const compiler = webpack(config);
const server = new WebpackDevServer(compiler, {
contentBase: '../dist/',
stats: {
colors: true
}
});
server.listen(3000, '127.0.0.1' ,err => {
if (err) {
console.log(err);
} else {
console.log('Dev Server listening on port 3000!\n');
open("http://localhost:3000");
}
});
webpack.config.js
import webpack from "webpack";
export default {
entry: [
"./app/index"
],
devtool: "inline-source-map",
output: {
path: __dirname + "/app/dist/", // Note: Physical files are only output by the production build task `npm run build`.
publicPath: "/",
filename: "bundle.js"
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
module: {
rules: [
{ test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}}
]
}
};
Project structure
On successful build a folder dist will be created inside the app folder which currently is not there.
Once the folder is created you can try by directly hitting the file path
http://localhost:3000/app/dist/yourfile
You can access your page via localhost:3000
When you access this path webpack dev server is searching for an index.html file to serve (like any other webserver). It can not find an index.html file because you have no index.html file. The index.html file is served from the static directory, which you have defined via property contentBase: '../dist/',.
but as I see you have no directory named dist and you have no index.html in this directory.
Your script is served from the public path, that is / in your config, so you have to reference this in your index.html
Solution:
Create directory dist and put an index.html file there with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="/bundle.js"></script>
</body>
</html>
For more information read here:
https://webpack.github.io/docs/webpack-dev-server.html

webpack dev server ignoring scss changes

I managed to compress / compile my js and scss files with webpack. The scss file gets extracted by the 'extract-text-webpack-plugin' into an external css file. Here is the code:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
require('es6-promise').polyfill();
module.exports = {
entry: ['./js/app'],
output: {
path: path.join(__dirname, 'js'),
publicPath: 'js',
filename: 'app.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false,
},
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new ExtractTextPlugin("../css/styles.min.css", {allChunks: false})
],
module: {
loaders: [{
test: /\.scss$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
}]
}
}
When I run now "webpack-dev-server js/app.js" - it gets my changes in the js file itself (alert for example) but does not remark changes in the css file.
This is the app.js:
var $ = require('jquery');
require('../css/styles.scss');
alert('Hi');
I guess the problem is connected to the ExtractTextPlugin. Then again I have no clue how to workaround. Any tips or ideas?
Okay, I got that going. When starting the webpack-dev-server, I'm just asking if we are in production enviroment:
const live = process.env.NODE_ENV === "production";
if(live) {
...
} else {
...
}
If we are not in production, it misses the ExtractTextPlugin out.
Finally to deploy my changes I type:
NODE_ENV=production webpack -p
One can also use a npm script to shorten this.

Categories

Resources