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(webpack): better merge for configs and fallback for async plugins #874

Merged
merged 2 commits into from Nov 28, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/logger/package.json
Expand Up @@ -39,6 +39,7 @@
"@types/debug": "^4.1.5"
},
"dependencies": {
"debug": "^4.1.1"
"debug": "^4.1.1",
"picocolors": "^1.0.0"
}
}
13 changes: 12 additions & 1 deletion packages/logger/src/index.ts
@@ -1,10 +1,11 @@
import genericDebug from 'debug';
import type { Debugger } from 'debug';
import pc from 'picocolors';

type LogLevel = 'error' | 'warn' | 'info' | 'debug';

const levels = ['error', 'warn', 'info', 'debug'];
const currentLevel = levels.indexOf(process.env.LINARIA_LOG || 'error');
const currentLevel = levels.indexOf(process.env.LINARIA_LOG || 'warn');

const linariaLogger = genericDebug('linaria');

Expand Down Expand Up @@ -61,3 +62,13 @@ export const debug = log.bind(null, 'debug');
export const info = log.bind(null, 'info');
export const warn = log.bind(null, 'warn');
export const error = log.bind(null, 'error');

export const notify = (message: string) => {
console.log(
pc.red(
message.replace(/(`.*?`)/g, (s) =>
pc.italic(s.substring(1, s.length - 1))
)
)
);
};
58 changes: 46 additions & 12 deletions packages/webpack4-loader/src/index.ts
Expand Up @@ -14,7 +14,7 @@ import findYarnWorkspaceRoot from 'find-yarn-workspace-root';
import type { RawSourceMap } from 'source-map';
import cosmiconfig from 'cosmiconfig';
import { EvalCache, Module, transform } from '@linaria/babel-preset';
import { debug } from '@linaria/logger';
import { debug, notify } from '@linaria/logger';

const workspaceRoot = findYarnWorkspaceRoot();
const lernaConfig = cosmiconfig('lerna', {
Expand Down Expand Up @@ -44,6 +44,11 @@ export default function webpack4Loader(

EvalCache.clearForFile(this.resourcePath);

const resolveOptionsDefaults = {
conditionNames: ['require'],
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
};

const {
sourceMap = undefined,
cacheDirectory = '.linaria-cache',
Expand All @@ -68,18 +73,47 @@ export default function webpack4Loader(
)
);

const resolveSync = enhancedResolve.create.sync(
// this._compilation is a deprecated API
// However there seems to be no other way to access webpack's resolver
// There is this.resolve, but it's asynchronous
// Another option is to read the webpack.config.js, but it won't work for programmatic usage
// This API is used by many loaders/plugins, so hope we're safe for a while
{
...(this._compilation?.options.resolve ?? {}),
// this._compilation is a deprecated API
// However there seems to be no other way to access webpack's resolver
// There is this.resolve, but it's asynchronous
// Another option is to read the webpack.config.js, but it won't work for programmatic usage
// This API is used by many loaders/plugins, so hope we're safe for a while
const webpackResolveOptions = this._compilation?.options.resolve;

// Resolved configuration contains empty list of extensions as a default value
// https://github.com/callstack/linaria/issues/855
if (webpackResolveOptions.extensions?.length === 0) {
delete webpackResolveOptions.extensions;
}

// Let's try to create a resolver with the webpack config
let resolveSync = enhancedResolve.create.sync({
...resolveOptionsDefaults,
...(this._compilation?.options.resolve ?? {}),
...resolveOptions,
mainFields: ['main'],
});

try {
// Try to resolve the current file
resolveSync(__dirname, __filename);
} catch (e) {
// Looks like one of the webpack plugins is async and the whole resolver became async
notify(
'The default webpack configuration cannot be used because some of the plugins are asynchronous. All plugins have been ignored. Please override `resolveOptions.plugins` in the Linaria configuration.'
);

// Fallback to synchronous resolve
resolveSync = enhancedResolve.create.sync({
...resolveOptionsDefaults,
...((webpackResolveOptions && {
alias: webpackResolveOptions.alias,
modules: webpackResolveOptions.modules,
}) ||
{}),
...resolveOptions,
mainFields: ['main'],
}
);
});
}

let result;

Expand Down
58 changes: 46 additions & 12 deletions packages/webpack5-loader/src/index.ts
Expand Up @@ -14,7 +14,7 @@ import findYarnWorkspaceRoot from 'find-yarn-workspace-root';
import type { RawSourceMap } from 'source-map';
import cosmiconfig from 'cosmiconfig';
import { EvalCache, Module, transform } from '@linaria/babel-preset';
import { debug } from '@linaria/logger';
import { debug, notify } from '@linaria/logger';

const workspaceRoot = findYarnWorkspaceRoot();
const lernaConfig = cosmiconfig('lerna', {
Expand All @@ -32,6 +32,11 @@ export default function webpack5Loader(

EvalCache.clearForFile(this.resourcePath);

const resolveOptionsDefaults = {
conditionNames: ['require'],
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
};

const {
sourceMap = undefined,
cacheDirectory = '.linaria-cache',
Expand All @@ -56,18 +61,47 @@ export default function webpack5Loader(
)
);

const resolveSync = enhancedResolve.create.sync(
// this._compilation is a deprecated API
// However there seems to be no other way to access webpack's resolver
// There is this.resolve, but it's asynchronous
// Another option is to read the webpack.config.js, but it won't work for programmatic usage
// This API is used by many loaders/plugins, so hope we're safe for a while
{
...(this._compilation?.options.resolve ?? {}),
// this._compilation is a deprecated API
// However there seems to be no other way to access webpack's resolver
// There is this.resolve, but it's asynchronous
// Another option is to read the webpack.config.js, but it won't work for programmatic usage
// This API is used by many loaders/plugins, so hope we're safe for a while
Copy link

Choose a reason for hiding this comment

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

this._compilation is undefined in the latest webpack

Copy link

Choose a reason for hiding this comment

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

const webpackResolveOptions = this._compilation?.options.resolve;

// Resolved configuration contains empty list of extensions as a default value
// https://github.com/callstack/linaria/issues/855
if (webpackResolveOptions.extensions?.length === 0) {
delete webpackResolveOptions.extensions;
}

// Let's try to create a resolver with the webpack config
let resolveSync = enhancedResolve.create.sync({
...resolveOptionsDefaults,
...(webpackResolveOptions ?? {}),
...resolveOptions,
mainFields: ['main'],
});

try {
// Try to resolve the current file
resolveSync(__dirname, __filename);
} catch (e) {
// Looks like one of the webpack plugins is async and the whole resolver became async
notify(
'The default webpack configuration cannot be used because some of the plugins are asynchronous. All plugins have been ignored. Please override `resolveOptions.plugins` in the Linaria configuration.'
);

// Fallback to synchronous resolve
resolveSync = enhancedResolve.create.sync({
...resolveOptionsDefaults,
...((webpackResolveOptions && {
alias: webpackResolveOptions.alias,
modules: webpackResolveOptions.modules,
}) ||
{}),
...resolveOptions,
mainFields: ['main'],
}
);
});
}

let result;

Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Expand Up @@ -11251,6 +11251,11 @@ performance-now@^2.1.0:
resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=

picocolors@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c"
integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==

picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.2, picomatch@^2.2.3:
version "2.3.0"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972"
Expand Down