Skip to content

Commit

Permalink
fix: import alias without tilde (#335)
Browse files Browse the repository at this point in the history
  • Loading branch information
cap-Bernardito committed Apr 17, 2020
1 parent 4604f20 commit 24021cd
Show file tree
Hide file tree
Showing 9 changed files with 133 additions and 15 deletions.
47 changes: 43 additions & 4 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
Expand Up @@ -75,6 +75,7 @@
"npm-run-all": "^4.1.5",
"prettier": "^2.0.4",
"standard-version": "^7.0.1",
"strip-ansi": "^6.0.0",
"webpack": "^4.42.1"
},
"keywords": [
Expand Down
37 changes: 34 additions & 3 deletions src/createWebpackLessPlugin.js
Expand Up @@ -31,7 +31,7 @@ function createWebpackLessPlugin(loaderContext) {
const resolve = loaderContext.getResolve({
mainFields: ['less', 'style', 'main', '...'],
mainFiles: ['_index', 'index', '...'],
extensions: ['.less', '.css', '...'],
extensions: ['.less', '.css'],
});

class WebpackFileManager extends less.FileManager {
Expand Down Expand Up @@ -61,7 +61,27 @@ function createWebpackLessPlugin(loaderContext) {
return filename;
}

async loadFile(filename, currentDirectory, options) {
resolveRequests(context, possibleRequests) {
if (possibleRequests.length === 0) {
return Promise.reject();
}

return resolve(context, possibleRequests[0])
.then((result) => {
return result;
})
.catch((error) => {
const [, ...tailPossibleRequests] = possibleRequests;

if (tailPossibleRequests.length === 0) {
throw error;
}

return this.resolveRequests(context, tailPossibleRequests);
});
}

async loadFile(filename, currentDirectory, options, ...args) {
const url = this.getUrl(filename, options);

const moduleRequest = urlToRequest(
Expand All @@ -71,7 +91,18 @@ function createWebpackLessPlugin(loaderContext) {

// Less is giving us trailing slashes, but the context should have no trailing slash
const context = currentDirectory.replace(trailingSlash, '');
const resolvedFilename = await resolve(context, moduleRequest);
let resolvedFilename;

try {
resolvedFilename = await this.resolveRequests(context, [
moduleRequest,
url,
]);
} catch (error) {
loaderContext.emitError(error);

return super.loadFile(filename, currentDirectory, options, ...args);
}

loaderContext.addDependency(resolvedFilename);

Expand Down
12 changes: 8 additions & 4 deletions test/__snapshots__/index.test.js.snap
Expand Up @@ -11,14 +11,18 @@ exports[`should fail if a file is tried to be loaded from include paths and with
in /test/fixtures/less/error-mixed-resolvers.less (line 3, column 0)"
`;

exports[`should provide a useful error message if the import could not be found 1`] = `
"Module build failed (from ./src/cjs.js):
exports[`should provide a useful error message if the import could not be found: errors 1`] = `
Array [
"ModuleBuildError: Module build failed (from \`replaced original path\`):
@import \\"not-existing\\";
^
Can't resolve './not-existing.less' in '/test/fixtures/less'
in /test/fixtures/less/error-import-not-existing.less (line 1, column 0)"
'not-existing' wasn't found. Tried - /test/fixtures/less/not-existing.less,npm://not-existing,npm://not-existing.less,not-existing.less
in /test/fixtures/less/error-import-not-existing.less (line 1, column 0)",
"ModuleError: Module Error (from \`replaced original path\`):
Can't resolve 'not-existing.less' in '/test/fixtures/less'",
]
`;

exports[`should provide a useful error message if there was a syntax error 1`] = `
Expand Down
11 changes: 11 additions & 0 deletions test/fixtures/less/import-webpack-aliases.less
@@ -0,0 +1,11 @@
@import "~fileAlias";
@import "~assets/folder/url-path.less";
@import "assets/folder/url-path.less";

body {
background: url(assets/resources/circle.svg);
}

.abs {
background: url(~assets/resources/circle.svg);
}
2 changes: 2 additions & 0 deletions test/helpers/createSpec.js
Expand Up @@ -21,6 +21,8 @@ const ignore = [
];
const lessReplacements = [
[/~some\//g, '../node_modules/some/'],
[/(~)?assets\//g, '../less/'],
[/~fileAlias/g, '../less/img.less'],
[/~(aliased-)?some"/g, '../node_modules/some/module.less"'],
];
const cssReplacements = [[/\.\.\/node_modules\/some\//g, '~some/']];
Expand Down
5 changes: 5 additions & 0 deletions test/helpers/getErrors.js
@@ -0,0 +1,5 @@
import normalizeErrors from './normalizeErrors';

export default (stats) => {
return normalizeErrors(stats.compilation.errors).sort();
};
24 changes: 24 additions & 0 deletions test/helpers/normalizeErrors.js
@@ -0,0 +1,24 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import stripAnsi from 'strip-ansi';

function removeCWD(str) {
const isWin = process.platform === 'win32';
let cwd = process.cwd();

if (isWin) {
// eslint-disable-next-line no-param-reassign
str = str.replace(/\\/g, '/');
// eslint-disable-next-line no-param-reassign
cwd = cwd.replace(/\\/g, '/');
}

return stripAnsi(str)
.replace(/\(from .*?\)/, '(from `replaced original path`)')
.replace(new RegExp(cwd, 'g'), '');
}

export default (errors) => {
return errors.map((error) =>
removeCWD(error.toString().split('\n').slice(0, 12).join('\n'))
);
};
9 changes: 5 additions & 4 deletions test/index.test.js
Expand Up @@ -4,6 +4,7 @@ import compile from './helpers/compile';
import moduleRules from './helpers/moduleRules';
import { readCssFixture, readSourceMap } from './helpers/readFixture';
import compareErrorMessage from './helpers/compareErrorMessage';
import getErrors from './helpers/getErrors';

const nodeModulesPath = path.resolve(__dirname, 'fixtures', 'node_modules');

Expand Down Expand Up @@ -88,10 +89,12 @@ test('should add all resolved imports as dependencies, including node_modules',
);
});

test('should resolve aliases as configured', async () => {
test('should resolve aliases in diffrent variants', async () => {
await compileAndCompare('import-webpack-alias', {
resolveAlias: {
'aliased-some': 'some',
fileAlias: path.resolve(__dirname, 'fixtures', 'less', 'img.less'),
assets: path.resolve(__dirname, 'fixtures', 'less'),
},
});
});
Expand Down Expand Up @@ -300,9 +303,7 @@ test('should provide a useful error message if the import could not be found', a
moduleRules.basic()
).catch((e) => e);

expect(err).toBeInstanceOf(Error);

compareErrorMessage(err.message);
expect(getErrors(err.stats)).toMatchSnapshot('errors');
});

test('should provide a useful error message if there was a syntax error', async () => {
Expand Down

0 comments on commit 24021cd

Please sign in to comment.