Skip to content

add alias option #120

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

Open
wants to merge 2 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
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ root = true

# Change these settings to your own preference
indent_style = space
indent_size = 2
indent_size = 4

# We recommend you to keep these unchanged
end_of_line = lf
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

## Directory-based project format:
.idea/
.vscode/
# if you remove the above rule, at least ignore the following:

# User-specific stuff:
Expand Down
43 changes: 38 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { resolve, dirname, isAbsolute } from 'path';

// options resolvers
import * as requireHooksOptions from './options_resolvers';

Expand Down Expand Up @@ -35,7 +34,37 @@ function findExpressionStatementChild(path, t) {
return findExpressionStatementChild(parent, t);
}


export function isRelativePath(nodePath) {
return nodePath.match(/^\.?\.\//);
}


const resolveAliasPath = (path, aliasOptions = []) => {
if (isRelativePath(path)) {
return false;
}

if (!aliasOptions.length) {
return path;
}
let res = path;
aliasOptions.forEach(item => {
/* eslint-disable-next-line prefer-const */
const [[key, value]] = Object.entries(item);

if (path.indexOf(key) === 0) {
// remove the dots if the value is relative
res = path.replace(key, value.replace(/^\.?\.\//, ''));
}
});
return `${process.cwd()}/${res}`;
};

export default function transformCssModules({ types: t }) {

let thisPluginOptions = null;

function resolveModulePath(filename) {
const dir = dirname(filename);
if (isAbsolute(dir)) return dir;
Expand All @@ -50,21 +79,25 @@ export default function transformCssModules({ types: t }) {
* @returns {Array} array of class names
*/
function requireCssFile(filepath, cssFile) {

let filePathOrModuleName = cssFile;

// only resolve path to file when we have a file path
if (!/^\w/i.test(filePathOrModuleName)) {
const from = resolveModulePath(filepath);
filePathOrModuleName = resolve(from, filePathOrModuleName);
}

// css-modules-require-hooks throws if file is ignored
try {
return require(filePathOrModuleName);
} catch (e) {
// As a last resort, require the cssFile itself. This enables loading of CSS files from external deps
let cssFilePath = cssFile;
if (thisPluginOptions.alias) {
cssFilePath = resolveAliasPath(cssFile, thisPluginOptions.alias);
}
try {
return require(cssFile);
return require(cssFilePath);
} catch (f) {
return {}; // return empty object, this simulates result of ignored stylesheet file
}
Expand Down Expand Up @@ -98,7 +131,6 @@ export default function transformCssModules({ types: t }) {
}

const cssMap = new Map();
let thisPluginOptions = null;

const pluginApi = {
manipulateOptions(options) {
Expand All @@ -120,10 +152,11 @@ export default function transformCssModules({ types: t }) {
}

const currentConfig = { ...defaultOptions, ...thisPluginOptions };
// this is not a css-require-ook config
// this is not a css-require-hook config
delete currentConfig.extractCss;
delete currentConfig.keepImport;
delete currentConfig.importPathFormatter;
delete currentConfig.alias;

// match file extensions, speeds up transform by creating one
// RegExp ahead of execution time
Expand Down
5 changes: 5 additions & 0 deletions test/fixtures/useAlias.expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

var styles = {
'className': 'styles__className___385m0 parent__block___33Sxl child__line___3fweh'
};
1 change: 1 addition & 0 deletions test/fixtures/useAlias.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import styles from 'my-app/styles.css';
20 changes: 20 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,4 +317,24 @@ describe('babel-plugin-css-modules-transform', () => {
);
});
});

describe('using alias for css files', () => {
it('use alias for css file path',() => {
expect(transform('fixtures/useAlias.js', {
alias: [{'my-app': './test'}]
}).code).to.be.equal(readExpected('fixtures/useAlias.expected.js'));
})

it('use alias for css file path', () => {
expect(transform('fixtures/useAlias.js', {
alias: [{ 'my-app': 'test' }]
}).code).to.be.equal(readExpected('fixtures/useAlias.expected.js'));
})

it('use alias for css file path', () => {
expect(transform('fixtures/useAlias.js', {
alias: [{ 'my-app': './test/' }]
}).code).to.be.equal(readExpected('fixtures/useAlias.expected.js'));
})
})
});
Loading