Skip to content

Commit

Permalink
feat: added support for dynamic imports
Browse files Browse the repository at this point in the history
  • Loading branch information
recursive-beast committed Mar 4, 2021
1 parent 5375055 commit feff91f
Show file tree
Hide file tree
Showing 5 changed files with 5,485 additions and 5 deletions.
17 changes: 15 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,23 @@ export default function externalAssets(pattern: FilterPattern): Plugin {
async renderChunk(code, chunk, outputOptions) {
const chunk_id = getOutputId(chunk.fileName, outputOptions);
const chunk_basename = path.basename(chunk_id);

const ast = parse(code, { sourceFileName: chunk_basename });
const rollup_context = this;

const customParser = {
parse(source: string) {
// Use rollup's internal acorn instance to parse `source`.
return rollup_context.parse(source, {
ecmaVersion: "latest",
locations: true, // Needed by `recast` to preserve code formatting.
});
},
};

const ast = parse(code, {
sourceFileName: chunk_basename,
parser: customParser,
});

visit(ast, {
visitLiteral(nodePath) {
const value = nodePath.node.value;
Expand Down
9 changes: 9 additions & 0 deletions tests/fixtures/src/index5.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import text from "./file1";
import sayHi from "./file2";

import("../assets/image.png")
.then(png => console.log(png))
.catch(err => console.error(err));

console.log(text);
sayHi();
11 changes: 8 additions & 3 deletions tests/output.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ test("treeshake.moduleSideEffects = false", outputSnapshotMacro,
}
);

// TODO: recast throws an error when a chunk contains dynamic imports,
// I tried to use acorn instead of the default esprima parser, but the error is still the same.
// I'll invistigate the source of that error later, but for now I'll only test static imports.
test("dynamic imports", outputSnapshotMacro,
{
input: "tests/fixtures/src/index5.js",
plugins: [
externalAssets("tests/fixtures/assets/*"),
],
}
);
Loading

0 comments on commit feff91f

Please sign in to comment.