Skip to content

Commit

Permalink
feat: successfully create an example
Browse files Browse the repository at this point in the history
It works πŸŽ‰πŸ’₯
  • Loading branch information
swashata committed Oct 7, 2018
1 parent 11ec4e6 commit 61fe269
Show file tree
Hide file tree
Showing 22 changed files with 690 additions and 126 deletions.
1 change: 1 addition & 0 deletions examples/plugin/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
31 changes: 31 additions & 0 deletions examples/plugin/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
version: '3'
services:
wordpress:
cap_add:
- SYS_ADMIN
devices:
- /dev/fuse
image: visiblevc/wordpress:latest
ports:
- 8080:80
- 443:443
volumes:
- ./:/app/wp-content/plugins/wpackio-plugin # Plugin development
environment:
DB_HOST: db # must match db service name below
DB_NAME: wordpress
DB_PASS: root # must match below
PLUGINS: >-
academic-bloggers-toolkit,
co-authors-plus,
[WP-API]https://github.com/WP-API/WP-API/archive/master.zip,
URL_REPLACE: localhost:8080
WP_DEBUG: 'true'
db:
image: mysql:5.7 # or mariadb:10
volumes:
- data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: root
volumes:
data: {}
176 changes: 176 additions & 0 deletions examples/plugin/inc/Enqueue.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
<?php
namespace WPackio;

class Enqueue {
/**
* Output path relative to the root of this plugin/theme.
*
* @var string
*/
private $outputPath;

/**
* Absolute path to plugin main file.
*
* @var string
*/
private $pluginPath;

/**
* Whether this is a plugin or theme.
*
* @var string
*/
private $type = 'plugin';

/**
* Plugin/Theme Version.
*
* @var string
*/
private $version = '';

/**
* Manifest cache to prevent multiple reading from filesystem.
*
* @var array
*/
static private $manifestCache = [];

/**
* Root absolute path to the output directory. With forward slash.
*
* @var string
*/
private $rootPath = '';

/**
* Root URL to the output directory. With forward slash.
*
* @var string
*/
private $rootUrl = '';

/**
* Create an instance of the Enqueue helper class.
*
* @param string $outputPath Output path relative to the root of this plugin/theme.
* @param string $version Version of your plugin/theme, used to generate query URL.
* @param string $type The type of enqueue, either 'plugin' or 'theme'.
* @param string|boolean $pluginPath If this is a plugin, then pass absolute path of the plugin main file, otherwise pass false.
*/
public function __construct( $outputPath, $version, $type = 'plugin', $pluginPath = false ) {
$this->outputPath = $outputPath;
$this->version = $version;
if ( ! in_array( $type, [ 'plugin', 'theme' ] ) ) {
throw new \LogicException( 'You can only enter "plugin" or "theme" as type.' );
}
$this->type = $type;
$this->pluginPath = $pluginPath;

// Set the root path and URL
$filepath = \trailingslashit( \get_template_directory() ) . $this->outputPath . '/';
$url = \trailingslashit( \get_template_directory_uri() ) . $this->outputPath . '/';
if ( 'plugin' === $this->type ) {
$filepath = \trailingslashit( dirname( $this->pluginPath ) ) . $this->outputPath . '/';
$url = \trailingslashit( \plugins_url( $this->outputPath, $this->pluginPath) );
}
$this->rootPath = $filepath;
$this->rootUrl = $url;
}

/**
* Enqueue all the assets for an entrypoint inside a source.
*
* @param string $dir The name of the source directory.
* @param string $entryPoint Which entrypoint would you like to enqueue.
* @param array $config Additional configuration.
* @return void
*/
public function enqueue( $dir, $entryPoint, $config ) {
$config = wp_parse_args( $config, [
'js' => true,
'css' => true,
'js_dep' => [],
'css_dep' => [],
'identifier' => false,
'in_footer' => true,
'media' => 'all',
] );
// Get the manifest
$manifest = $this->getManifest( $dir );
// Get the entrypoint
if ( ! isset( $manifest['wpackioEp'][ $entryPoint ] ) ) {
throw new \LogicException( 'No entry point found in the manifest' );
}
$enqueue = $manifest['wpackioEp'][ $entryPoint ];

// Set the identifier
$identifier = $config['identifier'];
if ( false === $identifier ) {
$identifier = 'wpackIo' . ucfirst( $dir ) . ucfirst( $entryPoint );
}

// Enqueue all js
$js_handles = [];
if ( $config['js'] && isset( $enqueue['js'] ) && count( (array) $enqueue['js'] ) ) {
foreach ( $enqueue['js'] as $index => $js ) {
$handle = $identifier . '_' . $index;
wp_enqueue_script( $handle, $this->getUrl( $js ), $config['js_dep'], $this->version, $config['in_footer']);
wp_localize_script( $handle, $identifier, [
'publicPath' => $this->getUrl( $dir . '/' ),
] );
$js_handles[] = $handle;
}
}

// Enqueue all CSS
$css_handles = [];
if ( $config['css'] && isset( $enqueue['css'] ) && count( (array) $enqueue['css'] ) ) {
foreach ( $enqueue['css'] as $index => $css ) {
$handle = $identifier . '_' . $index . '_css';
wp_enqueue_style( $handle, $this->getUrl( $css ), $config['css_dep'], $this->version, $config['media'] );
$css_handles[] = $handle;
}
}
}

/**
* Get Url of an asset.
*
* @param string $asset Asset as recovered from manifest.json
* @return string Complete URL.
*/
protected function getUrl( $asset ) {
return $this->rootUrl . $asset;
}

/**
* Get manifest from cache or from file.
*
* @param string $dir The Source directory.
* @return array wpackio compatible manifest item.
*/
protected function getManifest( $dir ) {
// If already present in the cache, then return it
if ( isset( self::$manifestCache[ $this->outputPath ][ $dir ] ) ) {
return self::$manifestCache[ $this->outputPath ][ $dir ];
}
// It is not, so get the json file
$filepath = $this->rootPath . $dir . '/manifest.json';

// Check if it exists
if ( ! file_exists( $filepath ) ) {
throw new \LogicException( sprintf( 'Manifest %s does not exist.', $filepath ) );
}
$manifest = json_decode( file_get_contents( $filepath ), true );
if ( $manifest === null || ! isset( $manifest['wpackioEp'] ) ) {
throw new \LogicException( sprintf( 'Invalid manifest file at %s. Either it is not valid JSON or wpackioEp does not exist.', $filepath ) );
}
if ( ! isset( self::$manifestCache[ $this->outputPath ] ) ) {
self::$manifestCache[ $this->outputPath ] = [];
}
self::$manifestCache[ $this->outputPath ][ $dir ] = $manifest;
return self::$manifestCache[ $this->outputPath ][ $dir ];
}
}
4 changes: 3 additions & 1 deletion examples/plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"license": "MIT",
"private": true,
"devDependencies": {
"@wpackio/scripts": "0.0.1"
"@wpackio/scripts": "0.0.1",
"autoprefixer": "^9.1.5",
"node-sass": "^4.9.3"
},
"scripts": {
"exstart": "wpackio-scripts start",
Expand Down
7 changes: 7 additions & 0 deletions examples/plugin/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
plugins: {
autoprefixer: {
browsers: '> 0.25%, not dead',
},
},
};
Binary file added examples/plugin/src/app/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions examples/plugin/src/app/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
body {
background-color: black !important;
}

.site-title a {
color: cyan !important;
}
24 changes: 24 additions & 0 deletions examples/plugin/src/app/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import './publicPathIndex';
import './index.css';
import imgURL from './image.png';
import logger from './modules/logger';

console.log(typeof process.env.NODE_ENV);
console.log(typeof process.env.BABEL_ENV);
console.log(process.env.BABEL_ENV);
console.log('Hello World', imgURL);
console.log('Hello World', imgURL);
console.log('Hello World', imgURL);

console.log('I am through stuff');
console.log('I am too');

logger();

if (module.hot) {
module.hot.accept('./modules/logger.js', () => {
/* eslint-disable global-require */
const newLogger = require('./modules/logger').default;
newLogger();
});
}
1 change: 1 addition & 0 deletions examples/plugin/src/app/mobile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('Hello Mobile');
6 changes: 6 additions & 0 deletions examples/plugin/src/app/modules/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default function logger() {
console.log('Huh');
console.log('Huh');
console.log('Huh');
console.log('Hot Reloaded');
}
7 changes: 7 additions & 0 deletions examples/plugin/src/app/publicPathIndex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* eslint-disable camelcase, no-underscore-dangle, no-undef */
if (process.env.NODE_ENV === 'production') {
// We set dynamic publicPath only for production
// In development, it is always handled by the internals
// As in the webpack config.
__webpack_public_path__ = window.wpackIoAppMain.publicPath;
}
29 changes: 29 additions & 0 deletions examples/plugin/wpackio-plugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
/**
* WPack.io Sample Plugin Development
*
* @package Wpackio
* @author Swashata Ghosh
* @copyright 2018 Swashata Ghosh
* @license GPL-2.0+
*
* @wordpress-plugin
* Plugin Name: WPack.io Sample Plugin Development
* Plugin URI: https://wpack.io
* Description: Test plugin development using wpackio-scripts
* Version: 1.0.0
* Author: Swashata Ghosh
* Author URI: https://swas.io
* Text Domain: wpack-io
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/

// Create an admin page
add_action( 'wp_enqueue_scripts', 'wpackio_plugin_enqueue' );
require_once dirname( __FILE__ ) . '/inc/Enqueue.php';

function wpackio_plugin_enqueue() {
$enqueue = new \WPackio\Enqueue( 'dist', '1.0.0', 'plugin', __FILE__ );
$enqueue->enqueue( 'app', 'main', [] );
}
54 changes: 54 additions & 0 deletions examples/plugin/wpackio.project.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
module.exports = {
// Project Identity
type: 'plugin', // Plugin or theme
slug: 'wpackio-plugin', // Plugin or Theme slug, basically the directory name under `wp-content/<themes|plugins>`
// Used to generate banners on top of compiled stuff
bannerConfig: {
name: 'WordPress WebPack Bundler',
author: 'Swashata Ghosh',
license: 'GPL-3.0',
link: 'https://wpack.io',
version: '1.0.0',
copyrightText:
'This software is released under the GPL-3.0 License\nhttps://opensource.org/licenses/GPL-3.0',
credit: true,
},
// Files we need to compile, and where to put
files: [
// If this has length === 1, then single compiler
{
name: 'app',
entry: {
main: ['./src/app/index.js'],
mobile: ['./src/app/mobile.js'],
},
filename: '[name].js',
// Extra webpack config to be passed directly
webpackConfig: undefined,
},
// If has more length, then multi-compiler
],
// Output path relative to the context directory
// We need relative path here, else, we can not map to publicPath
outputPath: 'dist',
// Project specific config
// Needs react?
hasReact: true,
// Needs sass?
hasSass: true,
// Externals
externals: {
jquery: 'jQuery',
},
// Webpack Aliases
alias: undefined,
// Show overlay on development
errorOverlay: true,
// Auto optimization by webpack
// Split all common chunks with default config
// <https://webpack.js.org/plugins/split-chunks-plugin/#optimization-splitchunks>
// Won't hurt because we use PHP to automate loading
optimizeSplitChunks: true,
// Usually PHP and other files to watch and reload when changed
watch: 'inc/**/*.php',
};
33 changes: 33 additions & 0 deletions examples/plugin/wpackio.server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module.exports = {
// Your LAN IP or host where you would want the live server
// Override this if you know your correct external IP (LAN)
// Otherwise, the system will always use localhost and will not
// work for external IP.
// This will also create some issues with file watching because for
// some reason, service-worker doesn't work on localhost?
// https://github.com/BrowserSync/browser-sync/issues/1295
// So it is recommended to change this to your LAN IP.
// If you intend to access it from your LAN (probably do?)
host: '192.168.1.144',
// Your WordPress development server address
proxy: 'http://localhost:8080',
// PORT on your localhost where you would want live server to hook
port: 3000,
// UI passed directly to browsersync
ui: {
port: 3001,
weinre: {
port: 8888,
},
},
// Whether to show the "BrowserSync Connected"
notify: false,
// Open the local URL, set to false to disable
open: 'external',
// BrowserSync ghostMode, set to false to completely disable
ghostMode: {
clicks: true,
scroll: true,
forms: true,
},
};
Loading

0 comments on commit 61fe269

Please sign in to comment.