workbox webpack 4 plugin unable to precache non-webpack assets - reactjs

I am looking to precache images for a PWA, using this documentation.
I have tried several iterations, but I am struggling with the globs.
Here's one instance of the plugin code on my webpack.config.js:
new InjectManifest({
swSrc: './client/sw-src.js',
swDest: '../sw.js',
exclude: [/\.twig$/],
globPatterns: ['/img/*.{svg,jpg,webp}']
}),
The directory structure is as follows:
/public
/dist => there's where the 'regular' webpack assets are
/img => directory I want to add to precache on top of /dist
...
I have also tried to use globDirectory, with no luck.
It works if I manually add the code below to my sw-src.js file, but that is not ideal and prone to errors.
workbox.precaching.precache([
'/img/circles.svg',
'/img/concept-1.jpg',
......
]);
workbox.precaching.addRoute();

One thing worth mentioning is that Workbox works with webpack assets that have been added to the compilation output. It's possible that you have files in the build context, like images in your repository, but they need to actually be required or otherwise added to the output.
One easy way to achieve this is to use copy-webpack-plugin. This is really useful when migrating to webpack from other build tools or when your dynamically constructing asset URLs and aren't using webpack loaders.
EDIT: Adding setup with actual solution:
This is the new directory setup:
/assets/img/ => origin directory for copy-webpack-plugin
/public
/dist => there's where the 'regular' webpack assets are
/img => destination directory for copy-webpack-plugin
And the actual code for copy-webpack-plugin and also adjusting the clean-webpack-plugin
new CleanWebpackPlugin(['public/dist/*.*', 'public/img/*.*']),
new CopyWebpackPlugin([
{ from: './assets/img/', to: '../img' },
]),

Related

Rails 7, React & Esbuild - Static assets not served in production

I have created a simple new Rails 7 project from scratch with Esbuild and React to get to know these, and they indeed feel like a step up from Webpack, except I can't manage to have my static files (ie image) served in production.
I have an Esbuild config file:
// esbuild.config.js
const path = require('path');
require("esbuild").build({
entryPoints: ["application.jsx"],
bundle: true,
outdir: path.join(process.cwd(), "app/assets/builds"),
absWorkingDir: path.join(process.cwd(), "app/javascript"),
publicPath: "assets",
sourcemap: true,
watch: process.argv.includes('--watch'),
plugins: [],
loader: {
'.js': 'jsx',
'.jpg': 'file',
'.png': 'file',
'.MOV': 'file'
},
}).catch(() => process.exit(1));
I store my images in the app/javascript/images/ folder, and import and use them in a React component like that (for example):
import MyImage from "./images/myimage.jpg"
import styled from "styled-components";
//...
const SomeStyledComponent = styled.div`
background-image: url(${MyImage});
`
In development, everything works fine, Esbuild copies the images in the app/assets/builds/ folder, fingerprints them, and prepends all the images url with the publicPath property of my Esbuild config. The above image for example then has the relative url assets/myimage-FINGERPRINT.jpg which is served correctly in development.
Then things get complicated in production (production here being just a Docker container built for production - I don't add the Dockerfile to keep things simple as I don't think it would help, but happy to provide it of course).
In my production.rb I have added the following:
config.public_file_server.enabled = true
(which will be replaced by an environment variable later)
The assets precompiling succeeds, and my images are in the app/public/assets/ folder, fingerprinted once more by Sprockets this time (from what I understand), but now I get 404. I have tried changing Esbuild publicPath and have tried to get the images directly in my browser, but whatever I try (assets, public, public/assets), nothing work and I am running out of ideas.
I have temporary fix which is to change the loader for images to dataurl, but that does not feel like a good practice, as my compiled javascript is going to explode.
Thank you for your help!
I ran into a similar issue, and by looking at the answers to https://github.com/rails/jsbundling-rails/issues/76 and this PR: https://github.com/rails/sprockets/pull/726/files
I was able to figure out the proper setup that works.
in the build options, I changed
publicPath: "assets",
to
publicPath: "/assets",
(included the leading /, which was missing before and causing the wrong path to be used)
and then added the following option
assetNames: "[name]-[hash].digested",
which, as you might be able to tell from the linked PR, would prevent Sprockets from adding an additional layer of fingerprinting.
I hope that helps.

REACT: Add multiple entry points in config-overrides.js file for multiple html files

I am new to React CRA (it is rewired as per doc in ant-design description for project setup) and facing issues in adding multiple entry points in webpack-config file.
I have 2 html files in public folder, index.html & stack.html.
-public
-index.html //runs on localhost:3000
-stack.html // runs on localhost:3000/stack.html
-src
-index.tsx
-stack.tsx
-config-overrides.ts
Default html index.html and index.tsx is used to boot and load react components.
I created stack.html file and accordingly i have created stack.tsx file as entry point to boot and load react components. I am unable to wire things up.
What configuration should be made to wire this up.
It is possible to do this, but you will need to eject from CRA. After that:
Add entry to the other html file in paths.js.
Update entry inside webpack.config.js and add the second html file entry (to be similar to the original entry).
Change the output file name inside webpack.config.js. Change static/j/bundle.js to static/js/[name].bundle.js.
Upadte webpack plugins to generate second file with injected JS scripts (also inside webpack.config.js).
Update the ManifestPlugin configuration to include the new entry point (also inside webpack.config.js).
Finally, there are two different steps for development and production.
For DEV, rewrite paths using the following in webpackDevServer.config.js (if you want to redirect all /admin to admin.html file):
verbose: true,
rewrites: [
{ from: /^/admin/, to: '/admin.html' },
],
For Production, this step is different for each provider. For Heroku, it is very easy, just create a static.json file with the following content:
{
"root": "build/",
"routes": {
"/admin**": "admin.html",
"/**": "index.html"
}
}
For full details and file diffs, see this post.
AFAIK, there are no good ways of doing this.
One way is to just use react-scripts and build multiple apps by copying and replacing index.html and index.js for each build. Something like
https://gist.github.com/jkarttunen/741fd48eb441137404a168883238ddc1
Also for CRA v3, there is an open PR for fixing this: https://github.com/facebook/create-react-app/pull/8249

How to preload Google Fonts from CDN with webpack

My goal is to import the fonts by:
#import url('https://fonts.googleapis.com/css?family=Poppins:i,100,200,300);
in my .scss file, then preload all the fonts by preload-webpack-plugin
After I deployed my bundle, the google fonts are applied, and the font request is like this:
Compare to the request which utilized #font-face in the .scss file, get the fonts downloaded to local then served by myself:
Only the file name of second one follows the name I defined in file-loader configuration:
exports.font = {
test: /\.(woff|woff2|ttf|eot)$/,
loader: 'file-loader',
query: {
name: '[name]-[hash:6].[ext]',
},
};
It's still reasonable for me, so my guess is, I think when Webpack is creating Dependency Graph css-loader interprets #import and url(), then file-loader duplicates the files to our dist folder, but if the source is from external, file-loader won't work on that.
Again, compare requests to CDN and local, the Sources section in Devtool shows me:
CDN:
Local:
When I request fonts from CDN there is a new folder gstatic, before I add preload-webpack-plugin, the fonts are requested dynamically when meet the new fonts family/style in the new pages, after I add preload-webpack-plugin, the fonts are preloaded only for the way which is sending fonts request to local.
exports.preloadWebpack = new PreloadWebpackPlugin({
rel: 'preload',
include: 'allAssets',
fileWhitelist: [/\.woff/, /\.woff2/, /\.ttf/],
as: 'font',
});
Any help is appreciated!!
You could consider using: Google Fonts Webpack Plugin,
and install it using npm in this way:
npm install #beyonk/google-fonts-webpack-plugin
More info.

How to point assets and html angular templates folder after building angularjs with webpack?

i am new to webpack, i have configured webpack to a working condition where my index.html file and budle.js file comes to /dist folder. iam aware that i can build css files too but for now i want to build js and run the app. please check the attached images for better understanding of the directory structure and the webpack build configuration.
My doubt is that if i run app from dist folder i would lose all the path of angular templates and image paths etc. how can i overcome this situation? any help is appreciated.
First of all, you need to know that the goal is to have a fully runnable stand alone application inside ./dist/ after build. All sourcefiles which are needed to run your application should be placed there. In that way you will be able to distribute your application by copy/upload/or-what-ever based on your ./dist/ directory. All other directories in your project are just for development. Those will be not a part of your distribution package.
Wrong approach: Trying to change the include path's in your application.
You need to copy or concat your sourcefiles (static files) into your distribution folder. I realy don't know why your views/templates are not stored in ./app/assets/ and not in ./app/views/ because ./app/views/ should be the correct path to store your views. Well, you need to copy your static sourcefiles. For example: You could use copy-webpack-plugin.
Your webpack config could look like this in the end:
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');
module.exports = {
context: path.join(__dirname, 'app'),
devServer: {
// This is required for older versions of webpack-dev-server
// if you use absolute 'to' paths. The path should be an
// absolute path to your build destination.
outputPath: path.join(__dirname, 'dist')
},
plugins: [
new CopyWebpackPlugin([
{
from: 'assets/**/*',
to: 'assets/'
},
{
from: 'views/**/*',
to: 'views/'
},
], {
ignore: [
],
// By default, we only copy modified files during
// a watch or webpack-dev-server build. Setting this
// to `true` copies all files.
copyUnmodified: true
})
]
};

Webpack: difference about entry between production and development environment

I'm reading tutorial about Webpack on this: Github Webpack tutorial In this, there is a section about config webpack for production and development.
Here is development configuration:
// webpack.config.dev.js
module.exports = {
devtool: 'cheap-eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index'
],
Here is production configuration:
// webpack.config.prod.js
module.exports = {
devtool: 'source-map',
entry: ['./src/index'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
I understand the difference in option of devtool. The thing I don't understand about entry. Why in production, entry is only about src/index but in development configuration, entry also includes webpack-dev-server
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index'
The lines 'webpack-dev-server/client?http://localhost:8080' and 'webpack/hot/dev-server' are configuring/defining which port to attach an active websocket to, in this case localhost:8080, and the content base which in this case is folder/path /client. In a production environment you would never run webpack-dev-server as your bundled client assets (bundle.js or similar) would be served by a server (IIS, Node, etc), that is why there are no webpack related items in entry of the production configuration.
The Webpack plugin in question webpack-dev-server is not required to run Webpack and compile your JS sources, it simply is a tool that can be used during the development process to watch for changes and reload changes.
Technically the entry array property in development could simply be the './src/index', but then it wouldn't enable the webpack-dev-server and/or it's hot module reloading. If you wanted to run webpack-dev-server without these configuration items then you'd then need to add command line arguments when starting webpack to specify the port and/or content base.
Hopefully that helps!
Here is the 2 things you should know before understanding:
As your linked in Webpack the confusing part, there are 3 types of entry: String Array and Object. As above code, that is array type. Meaning of entry array is: Webpack will merged all those javascript files in array together. This is often unnecessary because Webpack is intelligent enough to know which javascript files need to merge while processing. You often need to do this to enhance some features from different javascript files that you don't include somewhere else in your code.
This is "little tricky" part. You see webpack/hot/dev-serverand webpack-dev-server/client?http://localhost:8080 look like a web url rather than some javascript files, right? If you check your project directory, you see there are those files: your_app_directory/node_modules/webpack/hot/dev-server.js and your_app_directory/node_modules/webpack-dev-server/client.js. And that is the real meaning: you are importing two javascript files from two modules webpack-dev-server and webpack.
Back again to your webpack configuration:
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/dev-server',
'./src/index'
],
That means we will merge three different javascript files together as point 2 I have figured out. As I explain in point 1, you will do this for enhancing some features. You include file webpack-dev-server/client.js for making a server for serving your code. You include file webpack/hot/dev-server.js for allowing your code autoloading. This is super useful when you in development mode without start/stop server each time you modify your code.

Resources