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

fix(utils): use plugin to add entries for webpack@5 #2839

Merged
merged 5 commits into from
Nov 17, 2020
Merged
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
59 changes: 59 additions & 0 deletions lib/utils/DevServerEntryPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Based on webpack/lib/DynamicEntryPlugin
Author Naoyuki Kanezawa @nkzawa
*/

'use strict';

const webpack = require('webpack');

// @ts-ignore
const EntryPlugin = webpack.EntryPlugin;

class DevServerEntryPlugin {
/**
* @param {string} context context path
* @param {string[]} entries entry paths
* @param {?Object | string} options entry options
*/
constructor(context, entries, options) {
if (!EntryPlugin) {
throw new Error(
'DevServerEntryPlugin is supported in webpack 5 or greater'
);
}

this.context = context;
this.entries = entries;
this.options = options || '';
}

/**
* Apply the plugin
* @param {Object} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.make.tapPromise('DevServerEntryPlugin', (compilation) =>
Promise.all(
this.entries.map(
(entry) =>
new Promise((resolve, reject) => {
compilation.addEntry(
this.context,
EntryPlugin.createDependency(entry, this.options),
this.options,
(err) => {
if (err) return reject(err);
resolve();
}
);
})
)
)
);
}
}

module.exports = DevServerEntryPlugin;
44 changes: 32 additions & 12 deletions lib/utils/addEntries.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const webpack = require('webpack');
const createDomain = require('./createDomain');
const DevServerEntryPlugin = require('./DevServerEntryPlugin');

/**
* A Entry, it can be of type string or string[] or Object<string | string[],string>
Expand All @@ -10,12 +11,12 @@ const createDomain = require('./createDomain');

/**
* Add entries Method
* @param {?Object} config - Webpack config
* @param {?Object} compiler - Webpack compiler
* @param {?Object} options - Dev-Server options
* @param {?Object} server
* @returns {void}
*/
function addEntries(config, options, server) {
function addEntries(compiler, options, server) {
// we're stubbing the app in this method as it's static and doesn't require
// a server to be supplied. createDomain requires an app with the
// address() signature.
Expand Down Expand Up @@ -54,7 +55,7 @@ function addEntries(config, options, server) {
hotEntry = require.resolve('webpack/hot/dev-server');
}
/**
* prependEntry Method
* prependEntry Method for webpack 4
* @param {Entry} originalEntry
* @param {Entry} additionalEntries
* @returns {Entry}
Expand All @@ -74,13 +75,7 @@ function addEntries(config, options, server) {
Object.keys(originalEntry).forEach((key) => {
// entry[key] should be a string here
const entryDescription = originalEntry[key];
if (typeof entryDescription === 'object' && entryDescription.import) {
clone[key] = Object.assign({}, entryDescription, {
import: prependEntry(entryDescription.import, additionalEntries),
});
} else {
clone[key] = prependEntry(entryDescription, additionalEntries);
}
clone[key] = prependEntry(entryDescription, additionalEntries);
});

return clone;
Expand Down Expand Up @@ -120,8 +115,11 @@ function addEntries(config, options, server) {
return defaultValue;
};

const compilers = compiler.compilers || [compiler];

// eslint-disable-next-line no-shadow
[].concat(config).forEach((config) => {
compilers.forEach((compiler) => {
const config = compiler.options;
/** @type {Boolean} */
const webTarget = [
'web',
Expand All @@ -145,7 +143,29 @@ function addEntries(config, options, server) {
additionalEntries.push(hotEntry);
}

config.entry = prependEntry(config.entry || './src', additionalEntries);
// use a plugin to add entries if available
// @ts-ignore
if (webpack.EntryPlugin) {
// use existing plugin if possible
let entryPlugin = config.plugins.find(
(plugin) => plugin.constructor.name === 'DevServerEntryPlugin'
);

if (entryPlugin) {
entryPlugin.entries = additionalEntries;
} else {
entryPlugin = new DevServerEntryPlugin(
compiler.context,
additionalEntries,
{} // global entry
);
config.plugins.push(entryPlugin);
entryPlugin.apply(compiler);
}
} else {
config.entry = prependEntry(config.entry || './src', additionalEntries);
compiler.hooks.entryOption.call(config.context, config.entry);
}

if (options.hot || options.hot === 'only') {
config.plugins = config.plugins || [];
Expand Down
9 changes: 1 addition & 8 deletions lib/utils/updateCompiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,15 @@ function updateCompiler(compiler, options) {

const compilers = [];
const compilersWithoutHMR = [];
let webpackConfig;
if (compiler.compilers) {
webpackConfig = [];
// eslint-disable-next-line no-shadow
compiler.compilers.forEach((compiler) => {
webpackConfig.push(compiler.options);
compilers.push(compiler);
if (!findHMRPlugin(compiler.options)) {
compilersWithoutHMR.push(compiler);
}
});
} else {
webpackConfig = compiler.options;
compilers.push(compiler);
if (!findHMRPlugin(compiler.options)) {
compilersWithoutHMR.push(compiler);
Expand All @@ -42,12 +38,9 @@ function updateCompiler(compiler, options) {
// the changes we are making to the compiler
// important: this relies on the fact that addEntries now
// prevents duplicate new entries.
addEntries(webpackConfig, options);
addEntries(compiler, options);
// eslint-disable-next-line no-shadow
compilers.forEach((compiler) => {
const config = compiler.options;
compiler.hooks.entryOption.call(config.context, config.entry);

const providePlugin = new webpack.ProvidePlugin({
__webpack_dev_server_client__: getSocketClientPath(options),
});
Expand Down
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
"npm-run-all": "^4.1.5",
"prettier": "^2.0.5",
"puppeteer": "^5.2.1",
"require-from-string": "^2.0.2",
"rimraf": "^3.0.2",
"standard-version": "^9.0.0",
"style-loader": "^1.2.1",
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/module-federation-config/entry1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use strict';

module.exports = 'entry1';
3 changes: 3 additions & 0 deletions test/fixtures/module-federation-config/entry2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use strict';

module.exports = 'entry2';
15 changes: 15 additions & 0 deletions test/fixtures/module-federation-config/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

module.exports = {
mode: 'development',
target: 'node',
context: __dirname,
entry: ['./entry1.js', './entry2.js'],
output: {
path: '/',
libraryTarget: 'umd',
},
infrastructureLogging: {
level: 'warn',
},
};
17 changes: 17 additions & 0 deletions test/fixtures/module-federation-config/webpack.multi.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

module.exports = [
{
mode: 'development',
target: 'node',
context: __dirname,
entry: ['./entry1.js', './entry2.js'],
output: {
path: '/',
libraryTarget: 'umd',
},
infrastructureLogging: {
level: 'warn',
},
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

module.exports = {
mode: 'development',
target: 'node',
context: __dirname,
entry: {
foo: './entry1.js',
main: ['./entry1.js', './entry2.js'],
},
output: {
path: '/',
libraryTarget: 'umd',
},
infrastructureLogging: {
level: 'warn',
},
};
55 changes: 55 additions & 0 deletions test/integration/ModuleFederation.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
'use strict';

const request = require('supertest');
const requireFromString = require('require-from-string');
const testServer = require('../helpers/test-server');
const simpleConfig = require('../fixtures/module-federation-config/webpack.config');
const objectEntryConfig = require('../fixtures/module-federation-config/webpack.object-entry.config');
const multiConfig = require('../fixtures/module-federation-config/webpack.multi.config');
const port = require('../ports-map').ModuleFederation;

describe('module federation', () => {
describe.each([
['simple multi-entry config', simpleConfig],
['object multi-entry config', objectEntryConfig],
['multi compiler config', multiConfig],
])('%s', (title, config) => {
let server;
let req;

beforeAll((done) => {
server = testServer.start(config, { port }, done);
req = request(server.app);
});

afterAll(testServer.close);

it('should use the last entry export', async () => {
const { text, statusCode } = await req.get('/main.js');
expect(statusCode).toEqual(200);
expect(text).toContain('entry1');

let exports;
expect(() => {
exports = requireFromString(text);
}).not.toThrow();

expect(exports).toEqual('entry2');
});

if (title === 'object multi-entry config') {
it('should support the named entry export', async () => {
const { text, statusCode } = await req.get('/foo.js');
expect(statusCode).toEqual(200);
expect(text).not.toContain('entry2');

let exports;
expect(() => {
exports = requireFromString(text);
}).not.toThrow();

expect(exports).toEqual('entry1');
});
}
});
});
1 change: 1 addition & 0 deletions test/ports-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const portsList = {
'static-publicPath-option': 1,
'contentBasePublicPath-option': 1,
bundle: 1,
ModuleFederation: 1,
};

let startPort = 8089;
Expand Down
Loading