Skip to content

Commit

Permalink
Merge pull request #106 from Netcentric/feature/webpack-tests
Browse files Browse the repository at this point in the history
add webpack tests
  • Loading branch information
easingthemes committed Jan 31, 2024
2 parents a727b51 + 5c432f8 commit 7fe6d61
Show file tree
Hide file tree
Showing 15 changed files with 369 additions and 672 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,4 @@ coverage/

# Bundle Analyser
frontend/stats.json
__snapshots__/
2 changes: 1 addition & 1 deletion config/babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
loader: 'babel-loader',
options: {
presets: [['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3 }]],
plugins: ['@babel/plugin-transform-runtime', '@babel/plugin-proposal-object-rest-spread']
plugins: ['@babel/plugin-transform-runtime']
}
}
};
757 changes: 208 additions & 549 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"@babel/plugin-transform-runtime": "^7.23.2",
"@babel/preset-env": "^7.23.2",
"autoprefixer": "^10.4.16",
"babel-loader": "^9.1.3",
"babel-loader": "9.1.2",
"core-js": "^3.6.5",
"eslint": "^8.51.0",
"eslint-webpack-plugin": "^4.0.1",
Expand Down
56 changes: 31 additions & 25 deletions tasks/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,42 @@ const renderStyles = require('../utils/renderStyles');

// extend log to proper say what file is running
module.exports = (config) => {
if (config && config.general && config.general.watch) {
try {
log(__filename, 'Watcher Sass / autoprefixer running...', '', 'info');
return new Promise((resolve) => {
if (config && config.general && config.general.watch) {
try {
log(__filename, 'Watcher Sass / autoprefixer running...', '', 'info');

const gaze = require('gaze');
const sassPattern = path.join(config.general.sourcesPath, `**/*.${config.general.sourceKey}.scss`);
const gaze = require('gaze');
const sassPattern = path.join(config.general.sourcesPath, `**/*.${config.general.sourceKey}.scss`);

gaze(sassPattern, function () {
// simple debounce with timeout for only save the last if several events are triggered
this.on('all', (event, file) => {
// trigger a save
const relativePath = path.relative(config.general.sourcesPath, path.dirname(file));
const fileName = path.basename(file)
.replace(config.general.sourceKey, config.general.bundleKey);
const destFile = path.join(relativePath, fileName);
gaze(sassPattern, function () {
// simple debounce with timeout for only save the last if several events are triggered
this.on('all', (event, file) => {
// trigger a save
const relativePath = path.relative(config.general.sourcesPath, path.dirname(file));
const fileName = path.basename(file)
.replace(config.general.sourceKey, config.general.bundleKey);
const destFile = path.join(relativePath, fileName);

// override to keep alive
config.stylelint.failOnError = false;
// override to keep alive
config.stylelint.failOnError = false;

renderStyles(file, destFile, config);
renderStyles(file, destFile, config);
});
});
} catch (e) {
log(__filename, 'Something is missing, you need install dev dependencies for this.', e.message, 'error');
}
} else {
log(__filename, 'Sass / autoprefixer running...', '', 'info');

// checking all entries at this configuration
const entries = generateEntries(config, 'scss');
const promises = Object.keys(entries).map(file => renderStyles(entries[file], file, config));
Promise.allSettled(promises).then((results) => {
log(__filename, 'Styles done', '', 'info');
resolve();
});
} catch (e) {
log(__filename, 'Something is missing, you need install dev dependencies for this.', e.message, 'error');
}
} else {
log(__filename, 'Sass / autoprefixer running...', '', 'info');

// checking all entries at this configuration
const entries = generateEntries(config, 'scss');
Object.keys(entries).forEach(file => renderStyles(entries[file], file, config));
}
});
};
13 changes: 5 additions & 8 deletions tasks/styles.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

const fs = require('fs');
const path = require('path');
const styles = require('./styles');
Expand All @@ -12,12 +11,10 @@ let entries = {
};
const { destinationPath, projectKey } = config.general;

beforeAll(async () =>
beforeAll(async () =>
await new Promise(async (r) => {
await styles(config);
setTimeout(() => {
r()
},1000)
r();
})
);

Expand All @@ -28,9 +25,9 @@ describe('Test task/styles.js', () => {
const ext = path.extname(file) === '.js' ? 'js' : 'css';
const fileName = `${file.split('.').slice(0, -1).join('.')}.${ext}`;
it(`Compile ${source} file and save ${entry} at destination folder`, async () => {
const bundleContent = fs.readFileSync(fileName, { encoding:'utf8', flag:'r' });
const sourceContent = fs.readFileSync(source, { encoding:'utf8', flag:'r' });
expect(bundleContent).not.toBe(sourceContent);
const bundleContent = fs.readFileSync(fileName, { encoding:'utf8', flag:'r' });
const sourceContent = fs.readFileSync(source, { encoding:'utf8', flag:'r' });
expect(bundleContent).not.toBe(sourceContent);
});
})
});
Expand Down
111 changes: 57 additions & 54 deletions tasks/webpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,68 +3,71 @@ const ESLintPlugin = require('eslint-webpack-plugin');

const { log } = require('../utils/log');
const generateEntries = require('../utils/generateEntries');

// extend log to proper say what file is running
module.exports = (config) => {
// checking all entries at this configuration
const entry = generateEntries(config);
return new Promise((r) => {
// checking all entries at this configuration
const entry = generateEntries(config);

// make sure destination path is the same config as output
if (config && config.general && config.general.destinationPath) {
config.output.path = config.general.destinationPath;
}
// make sure destination path is the same config as output
if (config && config.general && config.general.destinationPath) {
config.output.path = config.general.destinationPath;
}

// setting rules for modules
const module = {
rules: config.general.modules.map(rule => config[rule])
};
// setting rules for modules
const module = {
rules: config.general.modules.map(rule => config[rule])
};

// log at the beginning
log(__filename, 'Webpack transpile running...', '', 'info');
// log at the beginning
log(__filename, 'Webpack transpile running...', '', 'info');

// extract from flatten configs to webpack
const { output, plugins, optimization, resolve, externals, stats, performance, cache, devServer, eslint} = config;
const { mode, watch, devtool } = config.general;
// check if there is any entry
plugins.push(new ESLintPlugin(eslint));
// extract from flatten configs to webpack
const { output, plugins, optimization, resolve, externals, stats, performance, cache, devServer, eslint } = config;
const { mode, watch, devtool } = config.general;
// check if there is any entry
plugins.push(new ESLintPlugin(eslint));

if (entry && Object.keys(entry).length > 0) {
// run webpack
webpack({
mode,
watch,
entry,
output,
module,
plugins,
optimization,
devtool,
resolve,
performance,
stats,
cache,
devServer,
...externals && { externals }
}, (err, stats) => {
// output the resulting stats.
if (stats && stats.toString) {
log(__filename, stats.toString({ colors: true }));
}
if (entry && Object.keys(entry).length > 0) {
// run webpack
webpack({
mode,
watch,
entry,
output,
module,
plugins,
optimization,
devtool,
resolve,
performance,
stats,
cache,
devServer,
...externals && { externals }
}, (err, stats) => {
// output the resulting stats.
if (stats && stats.toString) {
log(__filename, stats.toString({ colors: true }));
}

if (!watch && (stats && stats.hasErrors())) {
log(__filename, stats.toString(), '', 'error');
process.exit(1);
}
if (!watch && (stats && stats.hasErrors())) {
log(__filename, stats.toString(), '', 'error');
process.exit(1);
}

if (err) {
log(__filename, err.toString(), '', 'error');
process.exit(1);
}
if (err) {
log(__filename, err.toString(), '', 'error');
process.exit(1);
}

// log completion
log(__filename, 'Webpack transpile ended', '', 'success');
});
} else {
log(__filename, 'No entries for webpack, nothing found', '', 'info');
}
// log completion
log(__filename, 'Webpack transpile ended', '', 'success');
r();
});
} else {
log(__filename, 'No entries for webpack, nothing found', '', 'info');
r();
}
});
};
36 changes: 36 additions & 0 deletions tasks/webpack.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const fs = require('fs');
const path = require('path');
const webpackTask = require('./webpack');
const defaults = require('../config');
const extendConfig = require('../utils/extendConfig');
const generateEntries = require('../utils/generateEntries');

let config = extendConfig('./test/.febuild', defaults);
let entries = {
...generateEntries(config, 'js')
};
const { destinationPath, projectKey } = config.general;

beforeAll(async () =>
await new Promise(async (r) => {
await webpackTask(config);
r();
})
);

describe('Test task/webpack.js', () => {
Object.keys(entries).forEach((entry) => {
const file = path.join(destinationPath, entry);
const source = entries[entry];
const ext = path.extname(file) === '.js' ? 'js' : 'css';
const fileName = `${file.split('.').slice(0, -1).join('.')}.${ext}`;
it(`Compile ${source} file and save ${entry} at destination folder`, async () => {
const bundleContent = fs.readFileSync(fileName, { encoding:'utf8', flag:'r' });
const sourceContent = fs.readFileSync(source, { encoding:'utf8', flag:'r' });
expect(bundleContent).not.toBe(sourceContent);
});
})
});



6 changes: 5 additions & 1 deletion test/src/publish/publish.src.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ class MainPublish {
constructor() {
this.value = randomInt(1, 10);
this.arr = [...[0, 1, 2]];
this.obj = {
name: 'test'
};
this.init();
}

init() {
console.log(`Hello World ${this.value}!`);
const { name } = this.obj;
console.log(`Hello World ${this.value}! ${name}`);
}
}
export const instace = new MainPublish();
8 changes: 0 additions & 8 deletions utils/__snapshots__/linterError.test.js.snap

This file was deleted.

11 changes: 0 additions & 11 deletions utils/__snapshots__/log.test.js.snap

This file was deleted.

3 changes: 2 additions & 1 deletion utils/extendConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ module.exports = (configPath, config) => {
}

// config merge
const extendedConfig = merge(config, override);
const copyConfig = merge({}, config);
const extendedConfig = merge(copyConfig, override);
return extendedConfig;
};
2 changes: 2 additions & 0 deletions utils/merge.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ module.exports = function merge(original = {}, newObject) {
&& !Array.isArray(newObject[prop])
&& !(newObject[prop] instanceof RegExp)) {
copy[prop] = merge(original[prop], newObject[prop]);
} else if (Array.isArray(newObject[prop])) {
copy[prop] = newObject[prop] ? [...newObject[prop]] : [...original[prop]];
} else {
copy[prop] = newObject[prop] || typeof newObject[prop] === 'boolean' ? newObject[prop] : original[prop];
}
Expand Down
28 changes: 16 additions & 12 deletions utils/renderStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,20 @@ const renderPostcss = require('../utils/renderPostcss');
const runStylelint = require('../utils/runStylelint');
const writeFile = require('../utils/writeFile');

module.exports = function renderStyles(file, dest, config) {
return runStylelint(
[file], config, () =>
renderSass(
dest, file, config, (result, outFile) =>
renderPostcss(
result, outFile, config, postCssResult =>
// only write file at the end
writeFile(outFile, postCssResult.css, true)
)
)
);
module.exports = async function renderStyles(file, dest, config) {
return new Promise((resolve) => {
runStylelint(
[file], config, () =>
renderSass(
dest, file, config, (result, outFile) =>
renderPostcss(
result, outFile, config, postCssResult => {
// only write file at the end
writeFile(outFile, postCssResult.css, true);
resolve();
}
)
)
);
});
};
5 changes: 4 additions & 1 deletion utils/writeFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ module.exports = function writeFile(filepath, content, override = false) {
const normalizePath = path.normalize(filepath);
// if is not set to not override
if (!override && fs.existsSync(normalizePath)) return;

const dir = path.dirname(normalizePath);
if (!fs.existsSync(dir)){
fs.mkdirSync(dir, { recursive: true });
}
// white it
fs.writeFileSync(normalizePath, content,
err => log(__filename, 'error', `could not write file: ${err.Error},'\n ${err.path}`, 'error'));
Expand Down

0 comments on commit 7fe6d61

Please sign in to comment.