Skip to content

Commit

Permalink
update asset handeling for blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiankaegy committed May 10, 2022
1 parent e2c4bb8 commit 84a61ac
Show file tree
Hide file tree
Showing 9 changed files with 5,627 additions and 840 deletions.
6,363 changes: 5,537 additions & 826 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions packages/toolkit/config/__tests__/webpack-basic-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ describe('webpack.config.js', () => {
'10up-toolkit': {
entry: entryBuildFiles,
paths: {
blocksDir: './includes2/blocks/',
srcDir: './assets2/',
cssLoaderPaths: ['./assets2/css', './includes2/blocks'],
copyAssetsDir: './assets2/',
Expand Down Expand Up @@ -178,6 +179,7 @@ describe('webpack.config.js', () => {
'10up-toolkit': {
entry: entryBuildFiles,
paths: {
blocksDir: './includes2/blocks/',
srcDir: './assets2/',
cssLoaderPaths: ['./assets2/css', './includes2/blocks'],
copyAssetsDir: './assets2/',
Expand Down
4 changes: 2 additions & 2 deletions packages/toolkit/config/filenames.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ module.exports = {
js: 'js/[name].js',
jsChunk: 'js/[name].[contenthash].chunk.js',
css: 'css/[name].css',
block: 'blocks/[name]/editor.js',
blockCSS: 'blocks/[name]/editor.css',
block: 'blocks/[name].js',
blockCSS: 'blocks/[name].css',
};
1 change: 1 addition & 0 deletions packages/toolkit/config/paths.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ module.exports = {
srcDir: './assets/',
cssLoaderPaths: ['./assets/css', './includes/blocks'],
copyAssetsDir: './assets/',
blocksDir: './includes/blocks/',
};
20 changes: 15 additions & 5 deletions packages/toolkit/config/webpack/__tests__/entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,24 @@ describe('entry module function', () => {
it('returns project mode entry config', () => {
const buildFiles = { entry: 'entry.js' };
expect(
entry({ isPackage: false, packageConfig: {}, projectConfig: {}, buildFiles }),
entry({
isPackage: false,
packageConfig: {},
projectConfig: { paths: { blocksDir: './includes2/blocks/' } },
buildFiles,
}),
).toEqual(buildFiles);
});

it('returns package mode entry config', () => {
const buildFiles = { entry: 'entry.js' };
expect(
entry({ isPackage: true, packageConfig: {}, projectConfig: {}, buildFiles }),
entry({
isPackage: true,
packageConfig: {},
projectConfig: { paths: { blocksDir: './includes2/blocks/' } },
buildFiles,
}),
).toEqual(buildFiles);

expect(
Expand All @@ -24,7 +34,7 @@ describe('entry module function', () => {
umd: 'index.umd.js',
libraryName: 'LibraryName',
},
projectConfig: {},
projectConfig: { paths: { blocksDir: './includes2/blocks/' } },
buildFiles: [],
}),
).toEqual({
Expand Down Expand Up @@ -54,7 +64,7 @@ describe('entry module function', () => {
main: 'index.js',
libraryName: 'LibraryName',
},
projectConfig: {},
projectConfig: { paths: { blocksDir: './includes2/blocks/' } },
buildFiles: [],
}),
).toEqual({
Expand All @@ -76,7 +86,7 @@ describe('entry module function', () => {
main: 'index.js',
libraryName: 'LibraryName',
},
projectConfig: {},
projectConfig: { paths: { blocksDir: './includes2/blocks/' } },
buildFiles: [],
}),
).toEqual({
Expand Down
56 changes: 55 additions & 1 deletion packages/toolkit/config/webpack/entry.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,67 @@
const { readFileSync } = require('fs');
const { dirname, extname, join, resolve } = require('path');
const { sync: glob } = require('fast-glob');

const removeDistFolder = (file) => {
return file.replace(/(^\.\/dist\/)|^dist\//, '');
};

module.exports = ({
isPackage,
projectConfig: { devServer },
projectConfig: { devServer, paths },
packageConfig: { packageType, source, main, umd, libraryName },
buildFiles,
}) => {
const blocksSourceDirectory = resolve(process.cwd(), paths.blocksDir);

// get all block.json files in the blocks directory
const blockMetadataFiles = glob(`${blocksSourceDirectory}/**/block.json`, {
absolute: true,
});

// add any additional entrypoints we find in block.json filed to the webpack config
const additionalEntrypoints = blockMetadataFiles.reduce((accumulator, blockMetadataFile) => {
// get all assets from the block.json file
const { editorScript, script, viewScript, style, editorStyle } = JSON.parse(
readFileSync(blockMetadataFile),
);

// generate a new entrypoint for each of the assets
[editorScript, script, viewScript, style, editorStyle]
.flat()
.filter((rawFilepath) => rawFilepath && rawFilepath.startsWith('file:')) // assets can be files or handles. we only want files
.forEach((rawFilepath) => {
// Removes the `file:` prefix.
const filepath = join(dirname(blockMetadataFile), rawFilepath.replace('file:', ''));

// get the entrypoint name from the filepath by removing the blocks source directory and the file extension
const entryName = filepath
.replace(extname(filepath), '')
.replace(blocksSourceDirectory, '')
.replace(/\\/g, '/');

// Detects the proper file extension used in the defined source directory.
const [entryFilepath] = glob(
`${blocksSourceDirectory}/${entryName}.([jt]s?(x)|?(s)css)`,
{
absolute: true,
},
);

if (!entryFilepath) {
// eslint-disable-next-line no-console
console.warn('There was no entry file found for', entryName);
return;
}

accumulator[entryName] = entryFilepath;
});
return accumulator;
}, {});

// merge the new entrypoints with the existing ones
Object.assign(buildFiles, additionalEntrypoints);

if (isPackage) {
const config = {};
const hasBuildFiles = Object.keys(buildFiles).length > 0;
Expand Down
10 changes: 9 additions & 1 deletion packages/toolkit/config/webpack/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = ({
hot,
},
packageConfig: { style },
buildFiles,
}) => {
const hasReactFastRefresh = hot && !isProduction;

Expand Down Expand Up @@ -93,7 +94,9 @@ module.exports = ({
return removeDistFolder(style);
}

return options.chunk.name.match(/-block$/) ? filenames.blockCSS : filenames.css;
return buildFiles[options.chunk.name].match(/\/blocks\//)
? filenames.blockCSS
: filenames.css;
},
chunkFilename: '[id].css',
}),
Expand All @@ -108,6 +111,11 @@ module.exports = ({
noErrorOnMissing: true,
context: path.resolve(process.cwd(), paths.copyAssetsDir),
},
{
from: '**/block.json',
context: path.resolve(process.cwd(), paths.blocksDir),
to: 'blocks/[path][name][ext]',
},
hasReactFastRefresh && {
from: fromConfigRoot('fast-refresh.php'),
to: '[path][name][ext]',
Expand Down
7 changes: 4 additions & 3 deletions packages/toolkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"bin": {
"10up-toolkit": "bin/10up-toolkit.js"
},
"bundleDependencies": [],
"dependencies": {
"@babel/core": "^7.17.8",
"@babel/eslint-parser": "^7.17.0",
Expand All @@ -38,12 +37,15 @@
"css-loader": "^6.7.1",
"cssnano": "^5.1.7",
"eslint-webpack-plugin": "^3.1.1",
"fast-glob": "^3.2.11",
"fs": "^0.0.1-security",
"html-webpack-plugin": "^5.5.0",
"ignore-emit-webpack-plugin": "2.0.6",
"image-minimizer-webpack-plugin": "^3.2.3",
"jest": "^27.5.1",
"mini-css-extract-plugin": "^2.6.0",
"minimist": "^1.2.6",
"path": "^0.12.7",
"postcss": "^8.4.12",
"postcss-editor-styles": "^0.3.0",
"postcss-import": "^14.1.0",
Expand Down Expand Up @@ -73,8 +75,7 @@
"devDependencies": {
"@10up/babel-preset-default": "^2.0.2",
"@10up/eslint-config": "^2.4.5",
"@10up/stylelint-config": "^2.0.0",
"glob": "^7.2.0"
"@10up/stylelint-config": "^2.0.0"
},
"peerDependencies": {
"@10up/babel-preset-default": "^2.0.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/toolkit/test-utils/resolver.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const glob = require('glob');
const { sync: glob } = require('fast-glob');

let mapping = {};
// Looks for "module-resolution.json" files in all the `__tests__` directories
glob.sync(`${__dirname}/../**/__tests__/modules-resolution.json`).forEach((file) => {
glob(`${__dirname}/../**/__tests__/modules-resolution.json`).forEach((file) => {
// For each of them, merges them in the "mapping" object
mapping = { ...mapping, ...require(file) };
});
Expand Down

0 comments on commit 84a61ac

Please sign in to comment.