Skip to content

Commit

Permalink
Fix wildcard imports and update dependencies (#30)
Browse files Browse the repository at this point in the history
* fix: wildcard imports

* chore: update dependencies and fix dependabot alert

* chore: update node version used in actions
  • Loading branch information
Dschungelabenteuer authored Nov 1, 2023
1 parent 50872d5 commit e0f268e
Show file tree
Hide file tree
Showing 27 changed files with 1,742 additions and 1,683 deletions.
7 changes: 7 additions & 0 deletions .changeset/cool-years-boil.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'vite-plugin-entry-shaking': patch
---

Fixed an issue where wildcard imports would break instead of be ignored. This led to further
considerations about some edge cases wildcard imports could cause. See
[this example](./examples/issue-29/src/main.ts) for further information.
5 changes: 5 additions & 0 deletions .changeset/polite-apricots-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vite-plugin-entry-shaking': patch
---

Updated dependencies and fixed dependabot alerts
2 changes: 1 addition & 1 deletion .github/actions/install/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ runs:
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 20

- uses: pnpm/action-setup@v2
name: Install pnpm
Expand Down
6 changes: 3 additions & 3 deletions examples/complete/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
"preview": "vite preview"
},
"devDependencies": {
"@yungezeit/eslint-config-typescript": "^0.0.12",
"typescript": "^4.6.4",
"vite": "^4.0.5",
"@yungezeit/eslint-config-typescript": "^0.0.13",
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-plugin-entry-shaking": "workspace:*"
}
}
6 changes: 3 additions & 3 deletions examples/issue-18/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
"preview": "vite preview"
},
"devDependencies": {
"@yungezeit/eslint-config-typescript": "^0.0.12",
"typescript": "^4.6.4",
"vite": "^4.0.5",
"@yungezeit/eslint-config-typescript": "^0.0.13",
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-plugin-entry-shaking": "workspace:*"
}
}
3 changes: 3 additions & 0 deletions examples/issue-29/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": ["@yungezeit/typescript"]
}
25 changes: 25 additions & 0 deletions examples/issue-29/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dev-dist
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
18 changes: 18 additions & 0 deletions examples/issue-29/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>vite-plugin-entry-shaking simple example</title>
</head>
<body>
<div id="app"></div>
<script
type="module"
src="/src/main.ts"
></script>
</body>
</html>
17 changes: 17 additions & 0 deletions examples/issue-29/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "vite-plugin-entry-shaking-example-issue29",
"type": "module",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"devDependencies": {
"@yungezeit/eslint-config-typescript": "^0.0.13",
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-plugin-entry-shaking": "workspace:*"
}
}
23 changes: 23 additions & 0 deletions examples/issue-29/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as Utils from '@utils';
import { C } from './utils/C';
import initExample from '../../init';

/**
* C is manually re-imported to illustrate potential collisions between
* tree-shaking its statement triggers and the effects it may have on the
* whole Utils state.
*
* In versions <= 0.3.2, such a scenario would result in `Utils` only exposing
* `A` and `B` because the served module would be the one that was proceeded
* (and cleaned up) in the early entry analyzis stage.
*
* Despite this being a weird practice, this could still lead to undesired
* and hard-to-track issues. Instead, in such scenarios, we should serve
* the original entry file.
*/

console.info(Utils, C);

if (import.meta.hot) {
initExample(import.meta, 'issue 29');
}
1 change: 1 addition & 0 deletions examples/issue-29/src/utils/C.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const C = 'c';
3 changes: 3 additions & 0 deletions examples/issue-29/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const A = 'a';
export const B = 'b';
export { C } from './C';
1 change: 1 addition & 0 deletions examples/issue-29/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
23 changes: 23 additions & 0 deletions examples/issue-29/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ESNext", "DOM"],
"moduleResolution": "Node",
"strict": true,
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"paths": {
"@utils": ["./src/utils"]
}
},
"include": ["src"]
}
38 changes: 38 additions & 0 deletions examples/issue-29/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { resolve } from 'path';
import type { PluginOption } from 'vite';
import { defineConfig } from 'vite';

import EntryShakingPlugin from 'vite-plugin-entry-shaking';

const pathToUtils = resolve(__dirname, 'src/utils');
let requestCount = 0;
let disabled = false;

const countRequestPlugin = (): PluginOption => ({
name: 'vite-count-request-plugin',
configResolved(config) {
disabled = !config.plugins.find((plugin) => plugin.name === 'vite-plugin-entry-shaking');
},
configureServer(server) {
server.ws.on('count-request:fetch', () => {
server.ws.send('count-request:refresh', { requestCount, disabled });
});
},
load() {
requestCount += 1;
},
});

export default defineConfig(async () => ({
resolve: {
alias: {
'@utils': pathToUtils,
},
},
plugins: [
await EntryShakingPlugin({
targets: [pathToUtils],
}),
countRequestPlugin(),
],
}));
6 changes: 3 additions & 3 deletions examples/simple/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
"preview": "vite preview"
},
"devDependencies": {
"@yungezeit/eslint-config-typescript": "^0.0.12",
"typescript": "^4.6.4",
"vite": "^4.0.5",
"@yungezeit/eslint-config-typescript": "^0.0.13",
"typescript": "^5.2.2",
"vite": "^4.5.0",
"vite-plugin-entry-shaking": "workspace:*"
}
}
21 changes: 15 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,20 @@
"changeset:version": "changeset version && pnpm install --lockfile-only"
},
"devDependencies": {
"@changesets/changelog-github": "^0.4.7",
"@changesets/cli": "^2.25.0",
"@yungezeit/eslint-config-base": "^0.0.12",
"eslint": "^8.46.0",
"eslint-config-prettier": "^8.8.0",
"prettier": "^2.8.8"
"@changesets/changelog-github": "^0.4.8",
"@changesets/cli": "^2.26.2",
"@yungezeit/eslint-config-base": "^0.0.13",
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"prettier": "^3.0.3"
},
"pnpm": {
"packageExtensions": {
"vite": {
"dependencies": {
"postcss": "^8.4.31"
}
}
}
}
}
22 changes: 11 additions & 11 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,19 @@
"vite": ">=2.0.0"
},
"dependencies": {
"es-module-lexer": "^1.0.3",
"magic-string": "^0.26.3"
"es-module-lexer": "^1.3.1",
"magic-string": "^0.30.5"
},
"devDependencies": {
"@types/node": "^18.7.18",
"@vitest/coverage-istanbul": "^0.23.4",
"@yungezeit/eslint-config-typescript": "^0.0.12",
"eslint": "^8.46.0",
"eslint-config-prettier": "^8.8.0",
"@types/node": "^20.8.10",
"@vitest/coverage-istanbul": "^0.34.6",
"@yungezeit/eslint-config-typescript": "^0.0.13",
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"ts-dedent": "^2.2.0",
"typescript": "^4.8.3",
"unbuild": "^0.8.11",
"vite": "^4.0.5",
"vitest": "^0.23.2"
"typescript": "^5.2.2",
"unbuild": "^2.0.0",
"vite": "^4.5.0",
"vitest": "^0.34.6"
}
}
37 changes: 36 additions & 1 deletion packages/core/src/analyze-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import type {
TargetImports,
} from './types';

import { addSourceQuerySuffix } from './urls';

const WILDCARD_IMPORT_PREFIX = 'import *';

/**
* Returns the import params of a single imported entity.
* @param importString Import statement string.
Expand Down Expand Up @@ -167,7 +171,7 @@ const resolveImportedCircularEntities = async (
};

/**
* Analyzes a single target import.
* Analyzes and transforms a single target import.
* @param src MagicString instance to prepare transforms.
* @param code Source code of the file.
* @param entries _reference_ - Map of parsed entry files.
Expand All @@ -187,13 +191,44 @@ const analyzeImportStatement = async (
endPosition: number,
resolver: ResolveFn,
) => {
const isWildCardImport = catchWildcardImport(src, code, startPosition, endPosition, entryPath);
if (isWildCardImport) return;

const namedImports = methods.getImportedNamedExports(code, startPosition, endPosition);
const imported = await methods.getImportsMap(entryExports, entryPath, namedImports, resolver);
const replacement = await methods.getImportReplacements(imported, entryPath, entries, resolver);

src.overwrite(startPosition, endPosition + 1, `${replacement.join(';\n')};`);
};

/**
* Catches and handles import statement is a wildcard import.
* @param src MagicString instance to prepare transforms.
* @param code Source code of the file.
* @param startPosition Start position of the import statement.
*/
const catchWildcardImport = (
src: MagicString,
code: string,
startPosition: number,
endPosition: number,
entryPath: any,
) => {
const isWildCardImport =
code.slice(startPosition, WILDCARD_IMPORT_PREFIX.length) === WILDCARD_IMPORT_PREFIX;

if (isWildCardImport) {
const [what] = code.slice(startPosition, endPosition).split('from');
src.overwrite(
startPosition,
endPosition + 1,
`${what.trim()} from "${addSourceQuerySuffix(entryPath)}";`,
);
}

return isWildCardImport;
};

const methods = {
getImportParams,
getImportedNamedExports,
Expand Down
16 changes: 10 additions & 6 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import { configureLogger } from './logger';
import { transformIfNeeded } from './transform';
import { mergeOptions } from './options';
import EntryAnalyzer from './analyze-entry';
import { parseId } from './urls';

export async function createEntryShakingPlugin(
userOptions: PluginOptions,
): Promise<PluginOption> {
export async function createEntryShakingPlugin(userOptions: PluginOptions): Promise<PluginOption> {
const options = mergeOptions(userOptions);
let logger: Logger;
let resolver: ResolveFn;
Expand Down Expand Up @@ -37,9 +36,14 @@ export async function createEntryShakingPlugin(
},

load(id) {
if (entries.has(id)) {
logger.info(`Serving mutated entry file ${id}`);
return entries.get(id)!.updatedSource;
const { url, serveSource } = parseId(id);
const entry = entries.get(url);

if (entry) {
const version = serveSource ? 'original' : 'mutated';
const output = serveSource ? entry.source : entry.updatedSource;
logger.info(`Serving ${version} entry file ${url}`);
return output;
}
},
};
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export async function transformImports(
await init;
const src = new MagicString(code);


for (const { n: targetPath, ss: startPosition, se: endPosition } of imports) {
const resolvedImport = targetPath && (await resolver(targetPath, id));
const entry = resolvedImport && entries.get(resolvedImport);
Expand Down
Loading

0 comments on commit e0f268e

Please sign in to comment.