Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: expose multiple constructors #52

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
// eslint-disable-next-line import/no-unresolved
module.exports = require('./lib').default;
module.exports = require('./lib');
129 changes: 129 additions & 0 deletions src/dynamic-cdn-webpack-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import readPkgUp from 'read-pkg-up';
import ExternalModule from 'webpack/lib/ExternalModule';
import resolvePkg from 'resolve-pkg';

import getResolver from './get-resolver';

export const pluginName = 'dynamic-cdn-webpack-plugin';
const moduleRegex = /^((?:@[a-z0-9][\w-.]+\/)?[a-z0-9][\w-.]*)/;

const getEnvironment = mode => {
switch (mode) {
case 'none':
case 'development':
return 'development';

default:
return 'production';
}
};

export default class DynamicCdnWebpackPlugin {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing about default exports

constructor({disable = false, env, exclude, only, verbose, resolver} = {}) {
if (exclude && only) {
throw new Error('You can\'t use \'exclude\' and \'only\' at the same time');
}

this.disable = disable;
this.env = env;
this.exclude = exclude || [];
this.only = only || null;
this.verbose = verbose === true;
this.resolver = getResolver(resolver);

this.modulesFromCdn = {};
}

apply(compiler) {
if (!this.disable) {
this.execute(compiler, {env: this.env || getEnvironment(compiler.options.mode)});
}
this.output(compiler);
}

execute(compiler, {env}) {
compiler.hooks.normalModuleFactory.tap(pluginName, nmf => {
nmf.hooks.factory.tap(pluginName, factory => async (data, cb) => {
const modulePath = data.dependencies[0].request;
const contextPath = data.context;

const isModulePath = moduleRegex.test(modulePath);
if (!isModulePath) {
return factory(data, cb);
}

const varName = await this.addModule(contextPath, modulePath, {env});

if (varName === false) {
factory(data, cb);
} else if (varName == null) {
cb(null);
} else {
cb(null, new ExternalModule(varName, 'var', modulePath));
}
});
});
}

async addModule(contextPath, modulePath, {env}) {
const isModuleExcluded = this.exclude.includes(modulePath) ||
(this.only && !this.only.includes(modulePath));
if (isModuleExcluded) {
return false;
}

const moduleName = modulePath.match(moduleRegex)[1];
const {pkg: {version, peerDependencies}} = await readPkgUp({cwd: resolvePkg(moduleName, {cwd: contextPath})});

const isModuleAlreadyLoaded = Boolean(this.modulesFromCdn[modulePath]);
if (isModuleAlreadyLoaded) {
const isSameVersion = this.modulesFromCdn[modulePath].version === version;
if (isSameVersion) {
return this.modulesFromCdn[modulePath].var;
}

return false;
}

const cdnConfig = await this.resolver(modulePath, version, {env});

if (cdnConfig == null) {
if (this.verbose) {
console.log(`❌ '${modulePath}' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json`);
}
return false;
}

if (this.verbose) {
console.log(`✔️ '${cdnConfig.name}' will be served by ${cdnConfig.url}`);
}

if (peerDependencies) {
const arePeerDependenciesLoaded = (await Promise.all(Object.keys(peerDependencies).map(peerDependencyName => {
return this.addModule(contextPath, peerDependencyName, {env});
})))
.map(x => Boolean(x))
.reduce((result, x) => result && x, true);

if (!arePeerDependenciesLoaded) {
return false;
}
}

this.modulesFromCdn[modulePath] = cdnConfig;

return cdnConfig.var;
}

output(compiler) {
compiler.hooks.afterCompile.tapAsync(pluginName, (compilation, cb) => {
for (const [name, cdnConfig] of Object.entries(this.modulesFromCdn)) {
compilation.addChunkInGroup(name);
const chunk = compilation.addChunk(name);
chunk.files.push(cdnConfig.url);
}

cb();
});
}
}
33 changes: 33 additions & 0 deletions src/html-dynamic-cdn-webpack-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// eslint-disable-next-line no-unused-vars
import HtmlWebpackPlugin from 'html-webpack-plugin';
import HtmlWebpackIncludeAssetsPlugin from 'html-webpack-include-assets-plugin';

import DynamicCdnWebpackPlugin, {pluginName} from './dynamic-cdn-webpack-plugin';

export default class HtmlDynamicCdnWebpackPlugin extends DynamicCdnWebpackPlugin {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: I feel there is no need to export this as default. We are renaming the exports in src/index.js, so might as well do a named export

output(compiler) {
const includeAssetsPlugin = new HtmlWebpackIncludeAssetsPlugin({
assets: [],
publicPath: '',
append: false
});

includeAssetsPlugin.apply(compiler);

compiler.hooks.afterCompile.tapAsync(pluginName, (compilation, cb) => {
const assets = Object.values(this.modulesFromCdn).map(
moduleFromCdn => moduleFromCdn.url
);

// HACK: Calling the constructor directly is not recomended
// But that's the only secure way to edit `assets` afterhand
includeAssetsPlugin.constructor({
assets,
publicPath: '',
append: false
});

cb();
});
}
}
171 changes: 2 additions & 169 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,169 +1,2 @@
import readPkgUp from 'read-pkg-up';
import HtmlWebpackIncludeAssetsPlugin from 'html-webpack-include-assets-plugin';
import ExternalModule from 'webpack/lib/ExternalModule';
import resolvePkg from 'resolve-pkg';

import getResolver from './get-resolver';

const pluginName = 'dynamic-cdn-webpack-plugin';
let HtmlWebpackPlugin;
try {
// eslint-disable-next-line import/no-extraneous-dependencies
HtmlWebpackPlugin = require('html-webpack-plugin');
} catch (err) {
HtmlWebpackPlugin = null;
}

const moduleRegex = /^((?:@[a-z0-9][\w-.]+\/)?[a-z0-9][\w-.]*)/;

const getEnvironment = mode => {
switch (mode) {
case 'none':
case 'development':
return 'development';

default:
return 'production';
}
};

export default class DynamicCdnWebpackPlugin {
constructor({disable = false, env, exclude, only, verbose, resolver} = {}) {
if (exclude && only) {
throw new Error('You can\'t use \'exclude\' and \'only\' at the same time');
}

this.disable = disable;
this.env = env;
this.exclude = exclude || [];
this.only = only || null;
this.verbose = verbose === true;
this.resolver = getResolver(resolver);

this.modulesFromCdn = {};
}

apply(compiler) {
if (!this.disable) {
this.execute(compiler, {env: this.env || getEnvironment(compiler.options.mode)});
}

const isUsingHtmlWebpackPlugin = HtmlWebpackPlugin != null && compiler.options.plugins.some(x => x instanceof HtmlWebpackPlugin);

if (isUsingHtmlWebpackPlugin) {
this.applyHtmlWebpackPlugin(compiler);
} else {
this.applyWebpackCore(compiler);
}
}

execute(compiler, {env}) {
compiler.hooks.normalModuleFactory.tap(pluginName, nmf => {
nmf.hooks.factory.tap(pluginName, factory => async (data, cb) => {
const modulePath = data.dependencies[0].request;
const contextPath = data.context;

const isModulePath = moduleRegex.test(modulePath);
if (!isModulePath) {
return factory(data, cb);
}

const varName = await this.addModule(contextPath, modulePath, {env});

if (varName === false) {
factory(data, cb);
} else if (varName == null) {
cb(null);
} else {
cb(null, new ExternalModule(varName, 'var', modulePath));
}
});
});
}

async addModule(contextPath, modulePath, {env}) {
const isModuleExcluded = this.exclude.includes(modulePath) ||
(this.only && !this.only.includes(modulePath));
if (isModuleExcluded) {
return false;
}

const moduleName = modulePath.match(moduleRegex)[1];
const {pkg: {version, peerDependencies}} = await readPkgUp({cwd: resolvePkg(moduleName, {cwd: contextPath})});

const isModuleAlreadyLoaded = Boolean(this.modulesFromCdn[modulePath]);
if (isModuleAlreadyLoaded) {
const isSameVersion = this.modulesFromCdn[modulePath].version === version;
if (isSameVersion) {
return this.modulesFromCdn[modulePath].var;
}

return false;
}

const cdnConfig = await this.resolver(modulePath, version, {env});

if (cdnConfig == null) {
if (this.verbose) {
console.log(`❌ '${modulePath}' couldn't be found, please add it to https://github.com/mastilver/module-to-cdn/blob/master/modules.json`);
}
return false;
}

if (this.verbose) {
console.log(`✔️ '${cdnConfig.name}' will be served by ${cdnConfig.url}`);
}

if (peerDependencies) {
const arePeerDependenciesLoaded = (await Promise.all(Object.keys(peerDependencies).map(peerDependencyName => {
return this.addModule(contextPath, peerDependencyName, {env});
})))
.map(x => Boolean(x))
.reduce((result, x) => result && x, true);

if (!arePeerDependenciesLoaded) {
return false;
}
}

this.modulesFromCdn[modulePath] = cdnConfig;

return cdnConfig.var;
}

applyWebpackCore(compiler) {
compiler.hooks.afterCompile.tapAsync(pluginName, (compilation, cb) => {
for (const [name, cdnConfig] of Object.entries(this.modulesFromCdn)) {
compilation.addChunkInGroup(name);
const chunk = compilation.addChunk(name);
chunk.files.push(cdnConfig.url);
}

cb();
});
}

applyHtmlWebpackPlugin(compiler) {
const includeAssetsPlugin = new HtmlWebpackIncludeAssetsPlugin({
assets: [],
publicPath: '',
append: false
});

includeAssetsPlugin.apply(compiler);

compiler.hooks.afterCompile.tapAsync(pluginName, (compilation, cb) => {
const assets = Object.values(this.modulesFromCdn).map(moduleFromCdn => moduleFromCdn.url);

// HACK: Calling the constructor directly is not recomended
// But that's the only secure way to edit `assets` afterhand
includeAssetsPlugin.constructor({
assets,
publicPath: '',
append: false
});

cb();
});
}
}
export {default as HtmlDynamicCdnWebpackPlugin} from './html-dynamic-cdn-webpack-plugin';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once we remove the default export, we can just do something like

export * from './html-dynamic-cdn-webpack-plugin';

export {default as DynamicCdnWebpackPlugin} from './dynamic-cdn-webpack-plugin';
4 changes: 2 additions & 2 deletions test/html-webpack-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import fs from 'mz/fs';
import test from 'ava';
import HtmlWebpackPlugin from 'html-webpack-plugin';

import DynamicCdnWebpackPlugin from '../src';
import {HtmlDynamicCdnWebpackPlugin} from '../src';

import runWebpack from './helpers/run-webpack';
import cleanDir from './helpers/clean-dir';
Expand All @@ -26,7 +26,7 @@ test('html-webpack-plugin', async t => {

plugins: [
new HtmlWebpackPlugin(),
new DynamicCdnWebpackPlugin()
new HtmlDynamicCdnWebpackPlugin()
]
});

Expand Down