Skip to content

Commit

Permalink
fix issue #13
Browse files Browse the repository at this point in the history
  • Loading branch information
PeterAlfredLee committed Nov 10, 2021
1 parent 350b2f3 commit d449b64
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 4 deletions.
38 changes: 34 additions & 4 deletions packages/vite-plugin-require-context/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ const DEFAULT_REGEXP: RegExp = /^.*$/
const REQUIRE_CONTEXT_STRING_PREFIX: string = '__require_context_for_vite'
const PLUGIN_NAME: string = '@originjs/vite-plugin-require-context'
const GENERATED_CODE_COMMENT: string = `// generated by ${PLUGIN_NAME}\n`
const requireContextRegex: RegExp = /require\.context\(([\w\W]+?)\)($|\)|;|\n|\r\n)/g

export default (options: PluginOptions = {}): Plugin => {
return {
name: 'vite:require-context',
async transform(code: string, id: string) {
const requireContextRegex: RegExp = /require\.context\(([\w\W]+?)\)($|;|\n|\r\n)/g
const nodeModulesPath: string = '/node_modules/'

// do not handle the files in node_modules
Expand All @@ -48,7 +48,8 @@ export default (options: PluginOptions = {}): Plugin => {

// there may be multiple calls of require.context. We need to handle them separately
requireContextMatches.forEach((requireContextMatch, index) => {
const params: string[] = requireContextMatch[1].split(',')
const { paramsSyntax, tobeReplacedSyntax } = handleRequireContextSyntax(requireContextMatch[0])
const params: string[] = paramsSyntax.split(',')
const directory: string = params[0] || ''
const recursive: boolean = (!params[1]) ? DEFAULT_USE_RECURSIVE : eval(params[1])
const regExp: RegExp = (!params[2]) ? DEFAULT_REGEXP : eval(params[2])
Expand All @@ -66,8 +67,8 @@ export default (options: PluginOptions = {}): Plugin => {
const generatedRequireContextEnd = `// end of generated code of ${requireContextFunctionName}\n`
addedCode += generatedRequireContextStart + importsString + key2FilesMapString + contextFunctionString + generatedRequireContextEnd
transformedCode = transformedCode.replace(
requireContextMatch[0],
requireContextFunctionName + ";"
tobeReplacedSyntax,
requireContextFunctionName
)
})

Expand All @@ -77,6 +78,35 @@ export default (options: PluginOptions = {}): Plugin => {
}
}

function handleRequireContextSyntax(originalSyntax: string) {
if (!originalSyntax.startsWith('require.context')) {
throw new Error(`Unexpected syntax met. Syntax does not start with 'require.context'`)
}

const stack = []
let paramsStart
let paramsEnd
for (let i = 0; i < originalSyntax.length; i++) {
if (originalSyntax.charAt(i) == '(') {
stack.push('(')
if (stack.length == 1) {
paramsStart = i + 1
}
continue;
}

if (originalSyntax.charAt(i) == ')') {
stack.pop()
if (stack.length == 0) {
paramsEnd = i
break;
}
}
}

return {'paramsSyntax': originalSyntax.substring(paramsStart, paramsEnd), 'tobeReplacedSyntax': originalSyntax.substring(0, paramsEnd + 1)}
}

/**
* Transform all the calls of require.context
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// generated by @originjs/vite-plugin-require-context

// start of generated code of __require_context_for_vite_function_0, generated by @originjs/vite-plugin-require-context

var __require_context_for_vite_map_0 = {};
function __require_context_for_vite_function_0(req) {
var id = __require_context_for_vite_function_0_resolve(req);
return __require_context_for_vite_map_0[req];
}
function __require_context_for_vite_function_0_resolve(req) {
if (req in __require_context_for_vite_map_0) {
return __require_context_for_vite_map_0[req];
}
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
__require_context_for_vite_function_0.keys = function __require_context_for_vite_function_0_keys() {
return Object.keys(__require_context_for_vite_map_0);
}
__require_context_for_vite_function_0.resolve = __require_context_for_vite_function_0_resolve
__require_context_for_vite_function_0.id = "__require_context_for_vite_function_0"
// end of generated code of __require_context_for_vite_function_0
const requireComponents = getFilesByContext(__require_context_for_vite_function_0);
11 changes: 11 additions & 0 deletions packages/vite-plugin-require-context/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,14 @@ test('require context can not find any matched files', () => {
expect(data.code).toBe(expectCode);
});
});

test('require context surrounded by another function', () => {
const code = 'const requireComponents = getFilesByContext(require.context(\'/test/components\', true, /\.nomatch$/));\n';
const id = process.cwd().replace(/\\/g, '/') + '/' + 'src' + '/' + 'main.js';
const resultCode = require_context.default().transform(code, id);
const expectCode = fs.readFileSync('./test/expects/surroundedByFunction.txt','utf-8');

return resultCode.then(data => {
expect(data.code).toBe(expectCode);
});
});

0 comments on commit d449b64

Please sign in to comment.