webpack callback when file is changed : Callback NOT static configuration - node.js

I configured webpack to watch the ./src directory , and it works fine ; any file belongs to ./src directory & when it is changed & saved , webpack refreshes the bundled files.
const conf = {
//....
plugins: [
new webpack.HotModuleReplacementPlugin(),
]
//...
}
I am looking now for a something like the following :
const conf = {
//....
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
onWatchedChange: function(filePath) { // 🔍 LOOKING for this 👈🏼
if(filePath.endsWith('.js'))
// run command line or do any thing
}
}
Assuming that I am looking a NodeJS solution in general, I am aware that a solution can be :
const fs = require('fs');
fs.watch('./src', {encoding: 'buffer'}, (eventType, filename) => {
if (filename)
console.log(filename);
// Prints: <Buffer ...>
});
How to integrate the last snippet within webpack-dev-server configuration ?
OR
Does webpack supports a callback similar to the proof of concept that I explained (onWatchedChange callback) ?

Related

Node JS: Compile .scss file to .css and .map.css via node js script

I am new to node js, its structure and so on.
I am trying to compile a .scss file into a .css and .map.css file using a node js script.
The script sass-dev.js is defined in my package.json:
"scripts": {
"sass-dev": "node ./scripts/sass-dev.js"
},
So I can run the script via npm run sass-dev. The script itself works correctly, so it compiles the utility.scss into utility.css. But I want also that a source map utility.map.css is created. Therefore I defined sourceMap: true in the options, but no additional file is created.
So, how can I compile a .css and .map.css file from my .scss?
sass-dev.js:
const fs = require('fs');
const path = require('path');
const sass = require('sass');
const sassFile = path.join(__dirname, '../sass/utility.scss').toString();
const cssFile = path.join(__dirname, '../css/utility.css').toString();
const mapFile = path.join(__dirname, '../css/utility.map.scss').toString();
sass.render(
{
file: sassFile,
sourceMap: true,
outFile: mapFile,
},
(error, result) => {
if (!error) {
fs.writeFileSync(cssFile, result.css, function (err) {
if (err) console.log(`Error appeared while writing file "${o}".`);
});
} else {
console.log(error.formatted);
console.log(`Error appeared in "${error.file}" !\nline: ${error.line}, column: ${error.column}\n${error.status}`);
}
}
);
In node-scss, setting the file paths will not automatically write the output to the file (both CSS and mappings), it is just used for references and you have to write the output to a file just like how you did for the CSS.
Also, outFile should be the path of the generated CSS file. If you set sourceMap to true, the map file will be automatically determined (by appending .map). Otherwise you can set sourceMap directly to a string to use that.
Finally, since you are using writeFileSync, you don't have to pass a callback function, simply wrap it around in try catch.
sass.render({
file: sassFile,
outFile: cssFile,
}, (err, result) => {
if (err) {
// Handle error
return;
}
try {
fs.writeFileSync(cssFile, result.css);
fs.writeFileSync(mapFile, result.map);
} catch (e) {
// Handle error
}
});

Webpack generates js files with css / scss files

Description
In webpack I am using mini-css-extract-plugin:
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[name].[hash].css',
})
]
To load scss files in chunk files:
{
test: /\.scss$/,
use: [
{ loader: MiniCssExtractPlugin.loader, options: {
hmr: isdev,
reloadAll: true
}
},
"css-loader",
"sass-loader",
]
}
When I load a scss with an dynamic import:
import(/* webpackChunkName: "test" */ 'test.scss')
It will generate a test.[hash].css containing the styles and a test.[hash].js:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[15],{
/***/ 81:
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ })
}]);
Problem
I want to minimize the delay and loaded files so I find it redundant to have a nearly empty test.[hash].js file.
Do you have a way to either include the scss in the js file (see Idea 1) or to not emit/use the nearly empty js file?
Idea 1: not using mini-css-extract-plugin
My first idea was not using mini-css-extract-plugin for dynamic imported scss, but this will include a lot css-base stuff in the js (https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/255).
Here is an extract of code that could interrest you. It's coded in live here, so there is maybe some error I don't know.
I use an alternative way but nearby inside my own project.
The behaviour is :
Use the Event Hook Plugin and call it when the webpack is done
Loop through each file
If file is css and have the same name as with js extension
Then remove the js file
const EventHooksPlugin = require('event-hooks-webpack-plugin');
const path = require('path');
const fs = require('fs');
const _ = require('underscore');
plugins: [
new EventHooksPlugin({
done: () => {
const publicDir = __dirname + '/public';
const files = fs.readdirSync(publicDir);
_.each(files, file => {
if (path.extname(file) !== '.css') { return ;}
const fileJs = file.replace('.css', '.js');
if (!fs.existsSync(fileJs)) {return;}
fs.unlinkSync(fileJs);
});
}
})
]

Different builds based on targeting client vs server code

I currently have 2 separate webpack builds for server rendered vs client rendered code. Is there an easy way to change the build output based on server/client build?
For example something like this:
// Have some code like this
if(is_client){
console.log('x.y.z')
} else {
server.log('x.y.z')
}
// Webpack outputs:
// replaced code in client.js
console.log('x.y.z')
// replaced code in server.js
server.log('x.y.z')
Have you tried anything like this?
// webpack.config.js
module.exports = () => ['web', 'node'].map(target => {
const config = {
target,
context: path.resolve('__dirname', 'src'),
entry: {
[target]: ['./application.js'],
},
output: {
path: path.resolve(__dirname, 'dist', target),
filename: '[name].js'
},
modules: { rules: ... },
plugins: [
new webpack.DefinePlugin({
IS_NODE: JSON.stringify(target === 'node'),
IS_WEB: JSON.stringify(target === 'web'),
}),
],
};
return config;
});
// later in your code
import logger from 'logger';
if (IS_NODE) {
logger.log('this is node js');
}
if (IS_WEB) {
console.log('this is web');
}
how the compilation works?
// client.bundle.js
import logger from 'logger';
// DefinePlugin creates a constant expression which causes the code below to be unreachable
if (false) {
logger.log('this is node js');
}
if (true) {
console.log('this is web');
}
Finally you will produce your build in production mode, so webpack will include a plugin called UglifyJS, this has a feature called dead code removal (aka tree shaking), so it will delete any unused/unreachable code.
and the final result will look like:
// node.bundle.js
import logger from 'logger';
console.log('this is node js');
//web.bundle.js
console.log('this is node js');

Webpack dll import is not defined

I am trying to put a bunch of libs on the DLL following guides like react-boilerplate and this one.
When I build and run, the DLL files are given as not defined.
I'm probably missing something I did a separated webpack to build the dll:
import webpack from 'webpack'
const library = '[name]'
export default {
entry: {
'lokka': ['lokka', 'lokka-transport-http', 'socket.io-client']
/** Other libs **/
},
output: {
filename: '[name].dll.js',
path: 'build/',
library: library
},
plugins: [
new webpack.DllPlugin({
path: 'build/[name]-manifest.json',
name: library
})
]
}
And added the references to the manifest.json
import webpack from 'webpack'
const desiredLibs = [
'lokka'
]
const plugins = desiredLibs.map((lib) => {
return new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: require(`../build/${lib}-manifest.json`)
})
})
export const dllReference = () => {
return { plugins }
}
export default dllReference
Was there anything else I should do?
On my case, it is complaining that lokka is not found when the code is run.
Turns out I (obviously) need to include the generated DLL on my scripts src AND copy it in the case of dev, since hot reloading would only serve the entry of it and it's dependencies, so for the dllReference and copy part it became:
import webpack from 'webpack'
import CopyWebpackPlugin from 'copy-webpack-plugin'
import path from 'path'
const desiredLibs = ['lokka', 'react', 'moment']
const copies = []
const plugins = desiredLibs.map((lib) => {
copies.push({
from: path.join(__dirname, `../compileResources/${lib}.dll.js`),
to: `dll`
})
return new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: require(`../compileResources/${lib}-manifest.json`)
})
})
plugins.push(
new CopyWebpackPlugin(copies)
)
/**
* Adds the dll references and copies the file
*/
export const dllReference = () => {
return { plugins }
}
export default dllReference
And then since I copied the dll's using the copy plugin I needed to add the scripts on the html. Really obvious on hindsight

How do I output webpack as a string using Node

I am trying to use Webpack to bundle a bunch of files. I have the following in my node code...
webpack({
entry: "./src/test",
output: {
path: __dirname,
filename: "bundle.js"
},
}, function(err, stats){
console.log("I would like to output the created js here");
})
This works fine creating a file called bundle.js but I can't figure out how to output as a string instead.
Basically what you can do is to read the file, and then work with it as you want.
e.g.
import webpack from 'webpack';
const config = require('../webpack.config');
const compiler = webpack(config);
compiler.run((err, stats) => {
const data = stats.toJson();
const app = data.assetsByChunkName.app[0] //here you can get the file name
// if you don't have chunks then you should use data.assets;
const file = fs.readFileSync('path to your output ' + app); //read the file
//now you can work with the file as you want.
});
//Basic webpack.config.js
module.exports = {
devtool: 'source-map',
entry: {
app: 'Some path' // you can have different entries.
entrie2 : ''
.... more entries
},
output: {
path: 'Some path'
}
}
Hope this help.

Resources