Skip to content

Commit

Permalink
Change base module ModuleDependency -> Dependency (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
koistya authored May 9, 2021
1 parent 3d371eb commit 8f7a3b8
Show file tree
Hide file tree
Showing 19 changed files with 6,876 additions and 61 deletions.
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.github
.vscode
.yarn
test
.yarnrc.yml
.pnp.js
yarn.lock
5 changes: 4 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"recommendations": ["arcanis.vscode-zipfs", "esbenp.prettier-vscode"]
"recommendations": [
"arcanis.vscode-zipfs",
"esbenp.prettier-vscode"
]
}
16 changes: 16 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Test",
"skipFiles": ["<node_internals>/**"],
"runtimeExecutable": "yarn",
"runtimeArgs": ["jest"]
}
]
}

Large diffs are not rendered by default.

12 changes: 1 addition & 11 deletions .yarn/sdks/prettier/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const {existsSync} = require(`fs`);
const {createRequire, createRequireFromPath} = require(`module`);
const {resolve, dirname} = require(`path`);
const {resolve} = require(`path`);

const relPnpApiPath = "../../../.pnp.js";

Expand All @@ -14,16 +14,6 @@ if (existsSync(absPnpApiPath)) {
// Setup the environment to be able to require prettier/index.js
require(absPnpApiPath).setup();
}

const pnpifyResolution = require.resolve(`@yarnpkg/pnpify`, {paths: [dirname(absPnpApiPath)]});
if (typeof global[`__yarnpkg_sdk_is_using_pnpify__`] === `undefined`) {
Object.defineProperty(global, `__yarnpkg_sdk_is_using_pnpify__`, {configurable: true, value: true});

process.env.NODE_OPTIONS += ` -r ${pnpifyResolution}`;

// Apply PnPify to the current process
absRequire(pnpifyResolution).patchFs();
}
}

// Defer to the real prettier/index.js your application uses
Expand Down
16 changes: 15 additions & 1 deletion .yarn/sdks/typescript/lib/tsserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const moduleWrapper = tsserver => {

function toEditorPath(str) {
// We add the `zip:` prefix to both `.zip/` paths and virtual paths
if (isAbsolute(str) && !str.match(/^\^zip:/) && (str.match(/\.zip\//) || str.match(/\$\$virtual\//))) {
if (isAbsolute(str) && !str.match(/^\^zip:/) && (str.match(/\.zip\//) || str.match(/\/(\$\$virtual|__virtual__)\//))) {
// We also take the opportunity to turn virtual paths into physical ones;
// this makes is much easier to work with workspaces that list peer
// dependencies, since otherwise Ctrl+Click would bring us to the virtual
Expand Down Expand Up @@ -66,6 +66,20 @@ const moduleWrapper = tsserver => {
: str.replace(/^\^?zip:/, ``);
}

// Force enable 'allowLocalPluginLoads'
// TypeScript tries to resolve plugins using a path relative to itself
// which doesn't work when using the global cache
// https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238
// VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but
// TypeScript already does local loads and if this code is running the user trusts the workspace
// https://github.com/microsoft/vscode/issues/45856
const ConfiguredProject = tsserver.server.ConfiguredProject;
const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype;
ConfiguredProject.prototype.enablePluginsWithOptions = function() {
this.projectService.allowLocalPluginLoads = true;
return originalEnablePluginsWithOptions.apply(this, arguments);
};

// And here is the point where we hijack the VSCode <-> TS communications
// by adding ourselves in the middle. We locate everything that looks
// like an absolute path of ours and normalize it.
Expand Down
2 changes: 1 addition & 1 deletion .yarn/sdks/typescript/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "typescript",
"version": "4.1.5-pnpify",
"version": "4.2.4-pnpify",
"main": "./lib/typescript.js",
"type": "commonjs"
}
2 changes: 1 addition & 1 deletion .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
yarnPath: .yarn/releases/yarn-2.4.0.cjs
yarnPath: .yarn/releases/yarn-2.4.1.cjs
13 changes: 6 additions & 7 deletions IgnoreAsyncImportsPlugin.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
/**
* @copyright 2021-present Kriasoft (https://git.io/JtoKE)
*
* @typedef {import("webpack").Compiler} Compiler
* @typedef {import("webpack").javascript.JavascriptParser} JavascriptParser
*/
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

const path = require("path");
const webpack = require("webpack");
const ImportDependency = require("./ImportDependency");

/**
* Excludes dynamically imported dependencies from the output bundle.
*
* @typedef {import("webpack").Compiler} Compiler
* @typedef {import("webpack").javascript.JavascriptParser} JavascriptParser
*/
class IgnoreAsyncImportsPlugin {
/**
Expand Down Expand Up @@ -67,7 +66,7 @@ class IgnoreAsyncImportsPlugin {
const dep = new ImportDependency(expr.source.value, expr.range);
dep.loc = expr.loc;
parser.state.module.addDependency(dep);
return true;
return false;
});
}
}
Expand Down
18 changes: 8 additions & 10 deletions ImportDependency.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Florent Cailhol @ooflorent
*/
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

"use strict";

const InitFragment = require("webpack/lib/InitFragment");
const ModuleDependency = require("webpack/lib/dependencies/ModuleDependency");
const Dependency = require("webpack/lib/Dependency");
const DependencyTemplate = require("webpack/lib/DependencyTemplate");

/** @typedef {import("webpack").sources.ReplaceSource} ReplaceSource */
/** @typedef {import("webpack").ChunkGraph} ChunkGraph */
/** @typedef {import("webpack").Dependency} Dependency */
/** @typedef {import("webpack").Dependency.UpdateHashContext} UpdateHashContext */
/** @typedef {import("webpack").util.Hash} Hash */

class ImportDependency extends ModuleDependency {
class ImportDependency extends Dependency {
constructor(request, range) {
super(request);
super();
this.request = request;
this.range = range;
}

Expand All @@ -41,21 +41,19 @@ class ImportDependency extends ModuleDependency {
serialize(context) {
const { write } = context;
write(this.request);
write(this.userRequest);
write(this.range);
super.serialize(context);
}

deserialize(context) {
const { read } = context;
this.request = read();
this.userRequest = read();
this.range = read();
super.deserialize(context);
}
}

class ImportDependencyTemplate extends ModuleDependency.Template {
class ImportDependencyTemplate extends DependencyTemplate {
/**
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {ReplaceSource} source the current replace source which can be modified
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ will be replaced with `Promise.resolve(...)`.

## Related Projects

- [Node.js API Starter](https://github.com/kriasoft/nodejs-api-starter) - Monorepo project template based on Yarn v2, GraphQL.js, React, and Relay.
- [GraphQL API and Relay Starter Kit](https://github.com/kriasoft/graphql-starter) - Monorepo template pre-configured with GraphQL API, React, and Relay.
- [Node.js API Starter Kit](https://github.com/kriasoft/node-starter-kit) - Project template pre-configured with PostgreSQL, OAuth, emails, and unit tests.

## Copyright

Expand Down
5 changes: 2 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/**
* @copyright 2021-present Kriasoft (https://git.io/JtoKE)
*/
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

const IgnoreAsyncImportsPlugin = require("./IgnoreAsyncImportsPlugin");

Expand Down
12 changes: 9 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "ignore-webpack-plugin",
"version": "0.2.0",
"version": "0.3.0",
"description": "Excludes dynamically imported dependencies from the output bundle.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest"
},
"repository": "kriasoft/ignore-webpack-plugin",
"keywords": [
Expand All @@ -28,7 +28,13 @@
"webpack": ">=5.0.0"
},
"devDependencies": {
"@yarnpkg/pnpify": "^3.0.0-rc.3",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"typescript": "^4.1.5"
"typescript": "^4.2.4",
"webpack": "^5.36.2"
},
"jest": {
"testEnvironment": "node"
}
}
52 changes: 52 additions & 0 deletions test/app.bundle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({

/***/ 50:
/***/ ((module) => {

/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

module.exports = async function () {
const module = await Promise.resolve({});
console.log(module);
};


/***/ })

/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __webpack_require__(50);
/******/
/******/ })()
;
4 changes: 4 additions & 0 deletions test/app.chunk.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

module.exports = "external";
7 changes: 7 additions & 0 deletions test/app.main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

module.exports = async function () {
const module = await import("./app.chunk");
console.log(module);
};
19 changes: 19 additions & 0 deletions test/bundle.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

const { readFileSync } = require("fs");
const { webpack } = require("webpack");
const config = require("./webpack.config");

test("bundle", function (done) {
const compiler = webpack(config, function (err, stats) {
expect(err).toBeNull();
expect(stats.compilation.errors).toMatchInlineSnapshot(`Array []`);

const bundle = readFileSync("./test/app.bundle.js", "utf-8");
expect(bundle.includes("external")).toBe(false);
expect(bundle.includes("Promise.resolve({})")).toBe(true);

done();
});
});
24 changes: 24 additions & 0 deletions test/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */

const { IgnoreAsyncImportsPlugin } = require("..");

module.exports = {
entry: {
main: "./app.main",
},

context: __dirname,

output: {
path: __dirname,
filename: "app.bundle.js",
chunkFilename: "app.bundle.[name].js",
},

optimization: {
minimize: false,
},

plugins: [new IgnoreAsyncImportsPlugin()],
};
Loading

0 comments on commit 8f7a3b8

Please sign in to comment.