webpack-contrib / closure-webpack-plugin Goto Github PK
View Code? Open in Web Editor NEWWebpack Google Closure Compiler and Closure Library plugin -
Home Page: https://developers.google.com/closure/
License: MIT License
Webpack Google Closure Compiler and Closure Library plugin -
Home Page: https://developers.google.com/closure/
License: MIT License
Make sure any existing source maps are provided to closure-compiler along with each input. Make sure the output source maps for each chunk are properly associated.
const browsers = {}
browsers['a'] = 'd'
browsers['a'] = 't'
browsers['c'] = 'b'
I need to preserve the following keys, but when I define an extern
in my configuration, they will be replaced.
How to use with React/create-react-app? I get this error when use CRA and run yarn build
(that's all I got in the console)
Using config:
{ mode: 'STANDARD' }, {
formatting: 'PRETTY_PRINT',
debug: true
}
Help please :_)
Hi,
I tried the same setup as the mixed module demo. Some ES6 modules files have goog.module.declareNamespace()
to be compatible with goog.require()
, so I customized the deps writer a bit so it can include those files in deps.js, e.g. goog.addDependency('path/to//app.js', ['a.b.c'], [], {'module':'es6'});
.
The output JS file looks fine and does include those ES6 module files with "goog.module.declareNamespace(a.b.c)'. But goog.require(a.b.c) returns undefined. So I wonder if there is a way to let Closure compiler to parse those "goog.module.declareNamespace"?
I only see this issue in development mode so far.
Thanks,
Lu
I'm trying out version 0.0.3. Here is my complete project setup: https://gist.github.com/tschaub/daf72e3927af15361ee261d7d3749a37/1ca75d3168e84a9dfc3b7e1df878a36b4c451b93
I first tried with mode: 'STANDARD'
and got no output (nothing on stdout and no bundle created). When I changed to mode: 'AGGRESSIVE_BUNDLE'
, I got the following:
/path/to/ol-webpack-closure/node_modules/closure-webpack-plugin/src/index.js:202
const compilerProcess = this.runCompiler(compilationOptions, (exitCode, stdOutData, stdErrData) => {
^
TypeError: this.runCompiler is not a function
at ClosureCompilerPlugin.aggressiveBundle (/path/to/ol-webpack-closure/node_modules/closure-webpack-plugin/src/index.js:202:34)
at Compilation.compilation.plugin (/path/to/ol-webpack-closure/node_modules/closure-webpack-plugin/src/index.js:64:16)
at Compilation.applyPluginsAsyncSeries (/path/to/ol-webpack-closure/node_modules/tapable/lib/Tapable.js:206:13)
at self.applyPluginsAsync.err (/path/to/ol-webpack-closure/node_modules/webpack/lib/Compilation.js:666:10)
at Compilation.applyPluginsAsyncSeries (/path/to/ol-webpack-closure/node_modules/tapable/lib/Tapable.js:195:46)
at sealPart2 (/path/to/ol-webpack-closure/node_modules/webpack/lib/Compilation.js:662:9)
at Compilation.applyPluginsAsyncSeries (/path/to/ol-webpack-closure/node_modules/tapable/lib/Tapable.js:195:46)
at Compilation.seal (/path/to/ol-webpack-closure/node_modules/webpack/lib/Compilation.js:605:8)
at applyPluginsParallel.err (/path/to/ol-webpack-closure/node_modules/webpack/lib/Compiler.js:508:17)
at /path/to/ol-webpack-closure/node_modules/tapable/lib/Tapable.js:289:11
at _addModuleChain (/path/to/ol-webpack-closure/node_modules/webpack/lib/Compilation.js:507:11)
at processModuleDependencies.err (/path/to/ol-webpack-closure/node_modules/webpack/lib/Compilation.js:477:14)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
If I change the this.runCompiler
call to a static ClosureCompilerPlugin.runCompiler
call, I get TypeError: (extraCommandArgs || []).slice is not a function
.
I'm at a loss about what I might be doing wrong. Any tips are appreciated. Thanks!
I have a minimal React setup here that outputs three chunks (runtime, common, and main). The plugin seems to only process the main chunk and output blank for the others.
closure-webpack-plugin@next
When I set mode: 'AGGRESSIVE_BUNDLE'
it's throw an error ReferenceError: window is not defined
I tried to set globalObject: 'this'
for output
but it did not help. With mode: 'STANDARD'
works fine.
Google Closure Library has a dynamic imports engine --- goog.module.ModuleManager, which can be used to lazy loading JS resource. This engine is different from webpack, thus it should be handled without webpackJsonp.
I have used ModuleManager successfully to realize JS lay loading with closure-webpack-plugin, only in case where entry chunks have no common dependence.
I have to use CommonChunksPlugin When entry chunks have common dependence, as mentioned in Readme. But webpack tries to handle child chunk(lazy loading chunk) with webpackJsonp, which will cause child chunk lazy loading failure. The reason is below:
closure-webpack-plugin/src/index.js
Lines 440 to 446 in 2786b26
I suggest adding an option: entryChunks
to use entryChunkWrapper
instead of webpackJsonp
.
Could you grant me pull request permission? I have done implemented it locally. @ChadKillingsworth
What is different with webpack-closure-compiler?
I'm really struggling to get this plugin working. Here's the relevant information:
Package version information:
"closure-webpack-plugin": "^2.0.0-rc.10",
"google-closure-compiler": "^20181209.0.0-webpack-beta",
"ts-loader": "^5.3.1",
"typescript": "^3.2.2",
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2"
I've created a minimal app that reproduces the problem.
In my src directory, I have three files:
index.html:
<!doctype html>
<html lang="en">
<head>
<title>Webpack Test</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
App.ts:
import * as Math from "./Math";
var resp = prompt("Number?");
var num = parseInt(resp, 10);
var sqr = Math.square(num);
console.log(sqr);
Math.ts:
export function square(x) {return x * x};
Here is my tsconfig.json file:
{
"compilerOptions": {
"moduleResolution": "classic",
"module": "amd",
"target": "es5",
"baseUrl": "./src/js/"
}
}
And my webpack.config.js file:
const path = require('path');
const ClosurePlugin = require('closure-webpack-plugin');
module.exports = {
mode: "development",
entry: './src/App',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: [".ts", ".js"],
},
module: {
rules: [ { test: /\.tsx?$/, loader: "ts-loader" } ]
},
optimization: {
minimize: true,
minimizer: [
new ClosurePlugin({ mode: 'AGGRESSIVE_BUNDLE', platform: "native"} ,
{ compilation_level: "ADVANCED" })
]
}
};
Here is the resulting main.js function (pretty printed for readability):
(function(__wpcc){'use strict';
"undefined" === typeof __wpcc.b && (__wpcc.b = function() {
});
__wpcc.b.b = "";
}).call(this || window, (window.__wpcc = window.__wpcc || {}));
(function(__wpcc){'use strict';
var c = {}, d;
!(d = [__wpcc.b, c], c = function(e, a) {
Object.defineProperty(a, "__esModule", {value:!0});
a.a = function(a) {
return a * a;
};
}.apply(c, d), void 0 !== c && c);
/*
./Math */
var f = {}, g;
!(g = [__wpcc.b, f, c], f = function(e, a, h) {
Object.defineProperty(a, "__esModule", {value:!0});
e = (0,window.prompt)("Number?");
window.console.log(h.a((0,window.parseInt)(e, 10)));
}.apply(f, g), void 0 !== f && f);
}).call(this || window, (window.__wpcc = window.__wpcc || {}));
In the browser, it asks for a number, but then produces this error:
Uncaught TypeError: Cannot read property 'a' of undefined
at Object.<anonymous> (main.js:5)
at main.js:5
at main.js:5
I then deactivate closure compiler by changing the relevant line in my webpack.config.js file ( minimize: false
). The resulting code works great in the browser. In case it helps, here's the uncompiled main.js file:
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/App.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/App.ts":
/*!********************!*\
!*** ./src/App.ts ***!
\********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports, __webpack_require__(/*! ./Math */ \"./src/Math.ts\")], __WEBPACK_AMD_DEFINE_RESULT__ = (function (require, exports, Math) {\n \"use strict\";\n Object.defineProperty(exports, \"__esModule\", { value: true });\n var resp = prompt(\"Number?\");\n var num = parseInt(resp, 10);\n var sqr = Math.square(num);\n console.log(sqr);\n}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n\n//# sourceURL=webpack:///./src/App.ts?");
/***/ }),
/***/ "./src/Math.ts":
/*!*********************!*\
!*** ./src/Math.ts ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, exports], __WEBPACK_AMD_DEFINE_RESULT__ = (function (require, exports) {\n \"use strict\";\n Object.defineProperty(exports, \"__esModule\", { value: true });\n function square(x) { return x * x; }\n exports.square = square;\n ;\n}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n\n//# sourceURL=webpack:///./src/Math.ts?");
/***/ })
/******/ });
Can you point me in the right direction? Or is this some sort of bug?
Thanks!
Plugin is incompatible with typescript compiler emiting commonjs modules as it doesn't unwrap .default
export as default export.
I've made a simple repo with reproduction of this case: https://github.com/mk0x9/webpack-closure-compiler-typescript-issue
You need just to
npm install
npm start
and open dist/index.html
in your browser.
When trying to use closure-compiler in prodution, I get this error:
ERROR in chunk main [entry]
js/app-5215f6aa2932715d3535.js
.\node_modules\react-redux\es\index.js 13f267e2a74d9134e6de911fe99c39de
RuntimeTemplate.moduleId(): Module .\node_modules\@babel\runtime\helpers\esm\inheritsLoose.js has no id. This should not happen.
The babel helper is here: https://github.com/babel/babel/blob/81c130ffc912c53f884268969675bfb30d564449/packages/babel-helpers/src/helpers.js#L425
At lines 426-430 there is the exact content of the exported inheritsLoose.js file.
What is wrong with it? How can it be fixed? Should I issue @babel, or is it compiler-related?
Help me please, my bundle is 1.2 MiB ๐ฅ
Thank you.
node v10.13
"closure-webpack-plugin": "2.0.1"
"google-closure-compiler": "20190301.0.0"
"@babel/runtime": "7.3.4"
"@babel/plugin-transform-runtime": "7.3.4"
"react-redux": "6.0.1"
EDIT:
Seems to get fixed by setting optimization: {"concatenateModules": false}
in webpack config.
However, then I get this error, and there is no more information about it (no stack trace, no log):
ERROR in java.lang.IllegalArgumentException: Enum constant undefined: STRICT
I'm just installed the Clorsure Webpack plugin as mentined in the docs:
yarn add closure-webpack-plugin@next google-closure-compiler@webpack-beta -D
The webpack.config.js file is as follows:
const path = require('path')
const webpack = require('webpack')
const ClosurePlugin = require('closure-webpack-plugin')
module.exports = {
entry: {
'dashboard': './pages/dashboard/entry.js',
'auth': './pages/auth/entry.js',
},
optimization: {
minimizer: [
new ClosurePlugin({mode: 'STANDARD'}, {
// compiler flags here
//
// for debuging help, try these:
//
formatting: 'PRETTY_PRINT',
debug: true,
renaming: false,
})
]
},
output: {
path: path.resolve(__dirname, 'static/build'),
filename: '[name].js'
},
};
When using command webpack --mode production
I'm getting the following error:
PS > npm run build
> [email protected] build C:\acme\webfront\src
> webpack --mode production
events.js:167
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
at doWrite (_stream_writable.js:406:19)
at writeOrBuffer (_stream_writable.js:394:5)
at Socket.Writable.write (_stream_writable.js:294:11)
at Socket.Writable.end (_stream_writable.js:579:10)
at Socket.end (net.js:544:31)
at process.nextTick (C:\acme\webfront\src\node_modules\closure-webpack-plugin\src\closure-compiler-plugin.js:820:31)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at onwriteError (_stream_writable.js:425:12)
at onwrite (_stream_writable.js:456:5)
at doWrite (_stream_writable.js:406:11)
at writeOrBuffer (_stream_writable.js:394:5)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:61:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `webpack --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\acme\AppData\Roaming\npm-cache\_logs\2018-12-17T06_50_34_865Z-debug.log
What I'm doing wrong?
Node v10.13.0
Webpack v4.25.1
closure-webpack-plugin: 2.0.0-rc.10
google-closure-compiler-java: 20181209.0.0-webpack-beta
google-closure-compiler-js: 20181209.0.0-webpack-beta
google-closure-compiler-linux: 20181209.0.0-webpack-beta
google-closure-compiler-osx: 20181209.0.0-webpack-beta
google-closure-compiler: 20181209.0.0-webpack-beta
It's possible for the same input to occur in multiple chunks. That's not supported by Closure-compiler. Need to detect this case and provide an intelligent warning to the user so they can correct it.
I'd like to use closure-webpack-plugin
with webpack v4.
Is anyone working on to support webpack v4?
Thanks!
I'm getting this Error, which breaks the compilation(:unamused:)
DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
{
// ...
"devDependencies": {
"webpack-cli": "3.1.2",
"webpack": "4.25.1",
"ts-loader": "5.3.0",
"typescript": "3.1.6",
"closure-webpack-plugin": "1.1.1"
}
}
const googleClosureCompilerPlugin = require('closure-webpack-plugin')
module.exports = {
mode: 'production',
target: 'web',
optimization: {
minimize: true,
minimizer: [new googleClosureCompilerPlugin({mode: 'AGGRESSIVE_BUNDLE', platform: 'native'},{
})]
},
//..
}
(node:22522) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
at ClosureCompilerPlugin.apply (./node_modules/closure-webpack-plugin/src/index.js:92:14)
at WebpackOptionsApply.process (./node_modules/webpack/lib/WebpackOptionsApply.js:468:16)
at webpack (./node_modules/webpack/lib/webpack.js:53:48)
at processOptions (./node_modules/webpack-cli/bin/cli.js:441:16)
at yargs.parse (./node_modules/webpack-cli/bin/cli.js:536:3)
at Object.parse (./node_modules/yargs/yargs.js:563:18)
at ./node_modules/webpack-cli/bin/cli.js:219:8
at Object.<anonymous> (./node_modules/webpack-cli/bin/cli.js:538:3)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (./node_modules/webpack/bin/webpack.js:155:2)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
Hello, we have problem with access to https://hub.docker.com/u/webpackcontrib/, @d3viant0ne is unavailable for a long time and we need restore access to organization, maybe you have this access? We can contact using email (my @sheo13666q @ gmail . com). Sorry for issue here.
Does this version of the google closure compiler take the angular_pass
flag? If so, is this the way to pass it?
const compilerFlags ={
angular_pass: true
};
new ClosurePlugin(
{
// ...
},
compilerFlags
),
Thanks in advance!
Adding the plugin throws errors during build:
(node:8496) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Class constructor HarmonyImportSpecifierDependencyTemplate cannot be invoked without 'new'
(node:8496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
How can this problem be solved?
config:
new ClosureWebpackPlugin({ mode: 'AGGRESSIVE_MODE' }, {})
I tried adding closure to our project, but somehow it failed. I created this repo that reproduces the error. Building fails with ERROR in Unexpected token u in JSON at position 0
The example works as expected when removing the minimiezer
array from optimization
.
OS: Windows 10
Node: v12.3.0
closure-webpack-plugin: 2.0.1
google-closure-compiler: 20190513.0.0
webpack: 4.31.0 (also tried 4.32.0)
Many libraries do not support --compilation_level=ADVANCED . One way to work around that is to compile my own code in advanced mode, then append the libraries and compile again in simple mode. This results in modest savings (because often libraries are the bulk of the bundle), but it also helps protect intellectual property (via property renaming), which can be important for businesses.
I have not seen an easy way to use the workflow I described with webpack. It would be great if this plugin could support it.
Enabling aggressive bundle mode pollutes window with __wpcc
. Looks like it used by two chunks to share references between them. Wouldn't it better to wrap both chunks in yet another closure and use closure's local variable for that?
Example chunk from the compiled bundle:
(function(__wpcc){'use strict';var g;"undefined"===typeof g&&(g=function(){});g.p="";}).call(this || window, (window.__wpcc = window.__wpcc || {}));
I was trying out the Webpack 4 prerelease branch, which worked as expected in STANDARD
mode. When switching to AGGRESSIVE_BUNDLE
mode however, compilation failed with the following error:
TypeError: Cannot read property 'userRequest' of undefined
at originalChunks.forEach (node_modules/closure-webpack-plugin/src/closure-compiler-plugin.js:351:40)
at Array.forEach (<anonymous>)
I had no additional flags set/changed. My webpack config for this test is very basic.
Thanks for your work on this project. Can't wait for an official Webpack 4 release. Let me know if you need any more info! I can provide a sample repo if needed.
I got an error while running this:
=>> yarn release
yarn run v1.7.0
$ rm -rf dist/* && webpack --progress --config webpack.release.js
/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/cli.js:244
throw err;
^
Error: Cannot find module '../schema/plugin.json'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (/Users/chen/repo/chenyong/ts-workflow/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object.<anonymous> (/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin/src/index.js:19:36)
at Module._compile (/Users/chen/repo/chenyong/ts-workflow/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (/Users/chen/repo/chenyong/ts-workflow/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object.<anonymous> (/Users/chen/repo/chenyong/ts-workflow/webpack.release.js:4:23)
at Module._compile (/Users/chen/repo/chenyong/ts-workflow/node_modules/v8-compile-cache/v8-compile-cache.js:178:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (/Users/chen/repo/chenyong/ts-workflow/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at WEBPACK_OPTIONS (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/convert-argv.js:133:13)
at requireConfig (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/convert-argv.js:135:6)
at /Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/convert-argv.js:142:17
at Array.forEach (<anonymous>)
at module.exports (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/convert-argv.js:140:15)
at yargs.parse (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/cli.js:241:39)
at Object.parse (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/node_modules/yargs/yargs.js:563:18)
at /Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/cli.js:219:8
at Object.<anonymous> (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack-cli/bin/cli.js:530:3)
at Module._compile (internal/modules/cjs/loader.js:689:30)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
after looking into the folder I found schema/
folder is missing:
=>> pwd
/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin
=>> l
CHANGELOG.md LICENSE README.md node_modules/ package.json src/
=>> cat package.json
{
"name": "closure-webpack-plugin",
"version": "1.0.0",
var test = module.id + "test"
module.exports = test
Webpack converts "module.id" to "module.i"
/***/ (function(module, exports, __webpack_require__) {
var test = module.i + "test"
module.exports = test
/***/ }),
and closure compiler will throw an error
ERROR from closure-compiler: variable module is undeclared
var test = module.i + "test"
^^^^^^^
also two quick fixes I had to make to get the code to run on my machine:
Line 202:
+ const compilerProcess = ClosureCompilerPlugin.runCompiler(compilationOptions, (exitCode, stdOutData, stdErrData) => {
- const compilerProcess = this.runCompiler(compilationOptions, (exitCode, stdOutData, stdErrData) => {
Line 288:
+ const compilerRunner = new ClosureCompiler(flags);
- const compilerRunner = new ClosureCompiler(flags, doneCallback);
Seems this plugin is using API that Webpack is no longer support.
=>> yarn release
yarn run v1.7.0
$ rm -rf dist/* && webpack --progress --config webpack.release.js
10% building modules 2/2 modules 0 active(node:9126) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
10% building modules 4/5 modules 1 active โฆ/repo/chenyong/ts-workflow/src/main.tsxโน ๏ฝขatl๏ฝฃ: Using [email protected] from typescript
โน ๏ฝขatl๏ฝฃ: Using tsconfig.json from /Users/chen/repo/chenyong/ts-workflow/tsconfig.json
92% chunk asset optimization unnamed compat plugin
/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Chunk.js:802
throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead");
^
Error: Chunk.parents: Use ChunkGroup.getParents() instead
at Chunk.get (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Chunk.js:802:9)
at isTargetChunk (/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin/src/index.js:688:22)
at allChunks.forEach (/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin/src/index.js:695:11)
at Array.forEach (<anonymous>)
at Function.buildChunkMap (/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin/src/index.js:694:15)
at ClosureCompilerPlugin.standardBundle (/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin/src/index.js:178:44)
at compilation.plugin (/Users/chen/repo/chenyong/ts-workflow/node_modules/closure-webpack-plugin/src/index.js:169:16)
at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:12:1)
at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/Hook.js:35:21)
at hooks.additionalAssets.callAsync.err (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Compilation.js:1270:36)
at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)
at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/Hook.js:35:21)
at hooks.optimizeTree.callAsync.err (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Compilation.js:1266:32)
at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)
at AsyncSeriesHook.lazyCompileHook [as _callAsync] (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/Hook.js:35:21)
at Compilation.seal (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Compilation.js:1203:27)
at hooks.make.callAsync.err (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Compiler.js:547:17)
at _done (eval at create (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)
at _err1 (eval at create (/Users/chen/repo/chenyong/ts-workflow/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:32:22)
at _addModuleChain (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Compilation.js:1054:12)
at processModuleDependencies.err (/Users/chen/repo/chenyong/ts-workflow/node_modules/webpack/lib/Compilation.js:980:9)
at process._tickCallback (internal/process/next_tick.js:61:11)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
https://github.com/webpack-contrib/closure-webpack-plugin/blob/master/src/index.js#L732
Closure compiler does proper code splitting, so only a single compilation is performed. To do this sources must be assigned to specific chunks and the relationship of chunks to one another (a module tree) properly provided to closure-compiler. The current logic should be reviewed to ensure this is done correctly.
I saw unknown type issues when I run the aggressive bundle mode with the webpack closure plugin. I imported a type through ES6 import, but that type is not recognized by the Compiler.
// Parent module
/** @typedef {number} */
export let TYPE;
// Child module
import {TYPE} from './parent.js';
/** @type {TYPE}*/ -------> Warning: Unknown type TYPE
const b = 123
However, it works fine in JScompiler debugger.
I also tested it by using Closure compiler npm module with advanced optimization, it works there too.
Can you share some thoughts on how to fix this unknown type issue? Thanks!
Node: v8.4.0
OSX: 10.13.6
Hello, me again!
My project is using Webpack's dynamic imports in a few spots, which means I have to require @babel/plugin-syntax-dynamic-import
. Im also using @babel/plugin-transform-runtime
to include the regeneratorRuntime
functions.
It seems like Closure is transforming regeneratorRuntime.mark()
into $a$.mark()
, but $a$
is not defined anywhere, therefore throwing a TypeError. Even in debug mode, it's transformed into $a$
, even though I see references to $regeneratorRuntime$
elsewhere in the file.
I'm not exactly sure where this issue belongs. (If this is the wrong place feel free to close it)
Any guidance would be appreciated. Thanks again for your work on this plugin!
Contrib standard as a base with whatever magic all of this is going to require.
Currently, An error(goog is not defined
) occurs when I use the following libraries together.
goog.require
(Closure Script)goog.module
(Closure Module)import/export
(ES Modules)Uncaught ReferenceError: goog is not defined
at Object.<anonymous> (app.js:29445)
at __webpack_require__ (app.js:20)
at Object.googPreviousLoaderState__ (app.js:29413)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:20513)
at __webpack_require__ (app.js:20)
at COMPILED (app.js:63)
at app.js:66
The following is a repository to reproduce it.
If I remove one of them, the error doesn't occur.
Thanks!
Hi, this looks like a very promising project. I tried to use it on my backend project
'use strict';
const nodeExternals = require('webpack-node-externals');
const ClosureCompilerPlugin = require('closure-webpack-plugin');
const jsRule = {
test: /\.js$/,
exclude: [/node_modules/],
};
module.exports = {
entry: './app/index.js',
output: {
filename: 'dist.js',
},
module: {
rules: [
jsRule
]
},
target: 'node',
externals: [nodeExternals()],
plugins: [
new ClosureCompilerPlugin({mode: 'AGGRESSIVE_BUNDLE'}, {
})
]
};
However webpack fails to build the final assets:
> webpack --config ./webpack.config.js --progress --profile --colors
852ms building modules
11ms sealing
1ms optimizing
0ms basic module optimization
1ms module optimization
1ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
0ms advanced chunk optimization
0ms module and chunk tree optimization
0ms chunk modules optimization
0ms advanced chunk modules optimization
4ms module reviving
1ms module order optimization
3ms module id optimization
0ms chunk reviving
0ms chunk order optimization
7ms chunk id optimization
7ms hashing
1ms module assets processing
17ms chunk assets processing
1ms additional chunk assets processing
0ms recording
91% additional asset processing/project/server/node_modules/closure-webpack-plugin/src/index.js:202
const compilerProcess = this.runCompiler(compilationOptions, (exitCode, stdOutData, stdErrData) => {
^
TypeError: this.runCompiler is not a function
at ClosureCompilerPlugin.aggressiveBundle (/project/server/node_modules/closure-webpack-plugin/src/index.js:202:34)
at Compilation.compilation.plugin (/project/server/node_modules/closure-webpack-plugin/src/index.js:64:16)
at Compilation.applyPluginsAsyncSeries (/project/server/node_modules/tapable/lib/Tapable.js:206:13)
at self.applyPluginsAsync.err (/project/server/node_modules/webpack/lib/Compilation.js:666:10)
at next (/project/server/node_modules/tapable/lib/Tapable.js:202:11)
at Compilation.compilation.plugin.callback (/project/server/node_modules/webpack/lib/ProgressPlugin.js:115:6)
at Compilation.applyPluginsAsyncSeries (/project/server/node_modules/tapable/lib/Tapable.js:206:13)
at sealPart2 (/project/server/node_modules/webpack/lib/Compilation.js:662:9)
at next (/project/server/node_modules/tapable/lib/Tapable.js:202:11)
at Compilation.compilation.plugin (/project/server/node_modules/webpack/lib/ProgressPlugin.js:111:6)
at Compilation.applyPluginsAsyncSeries (/project/server/node_modules/tapable/lib/Tapable.js:206:13)
at Compilation.seal (/project/server/node_modules/webpack/lib/Compilation.js:605:8)
at applyPluginsParallel.err (/project/server/node_modules/webpack/lib/Compiler.js:508:17)
at /project/server/node_modules/tapable/lib/Tapable.js:289:11
at _addModuleChain (/project/server/node_modules/webpack/lib/Compilation.js:507:11)
at processModuleDependencies.err (/project/server/node_modules/webpack/lib/Compilation.js:477:14)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dist:webpack: `webpack --config ./webpack.config.js --progress --profile --colors`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dist:webpack script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Tried with node 6.10 and v8.4 using webpack 3.8.1
Initial container: Install, lint, security, unit tests?, cache layer => 4x parallel run integration tests for webpack@latest/next on closure Oracle JDK 8 / 9 prebuilt containers.
Matrix: webpack@latest, webpack@next, closure-compiler w/ JDK8 ( container ), closure-compiler w/ JDK9 ( container )
TBD: Given the nature of this plugin, performance should be a part of the validations for merge.
here is an example compiling my project
zh99998deMacBook-Pro:dsv zh99998$ google-closure-compiler --externs /Users/zh99998/DS/dsv/src/externs.js --rewrite_polyfills false --compilation_level ADVANCED --language_in ECMASCRIPT_2017 --language_out=ECMASCRIPT_2017 /Users/zh99998/DS/dsv/public/build.js
2ๆ 01, 2018 2:20:22 ไธๅ com.google.javascript.jscomp.PhaseOptimizer$NamedPass process
่ญฆๅ: Skipping pass inlineTypeAliases
2ๆ 01, 2018 2:20:22 ไธๅ com.google.javascript.jscomp.PhaseOptimizer$NamedPass process
่ญฆๅ: Skipping pass resolveTypes
2ๆ 01, 2018 2:20:22 ไธๅ com.google.javascript.jscomp.PhaseOptimizer$NamedPass process
่ญฆๅ: Skipping pass inferTypes
...
/Users/zh99998/DS/dsv/public/build.js:68: WARNING - Suspicious code. This code lacks side-effects. Is there a bug?
Object.create(null),x=c.zC=(0,a.default)()},function(b){function c(b,c){var g=b[1]||"",m=b[3];return m?c&&"function"===typeof btoa?(b=a(m),c=m.NY.map(function(a){return"/*# sourceURL="+m.aea+a+" */"}),[g].concat(c).concat([b]).join("\n")):""+g:g}function a(a){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"}b.m=function(a){var b=[];b.toString=function(){return this.map(function(b){var g=c(b,a);return b[2]?"@media "+
^
...
0 error(s), 156 warning(s)
then https://github.com/webpack-contrib/closure-webpack-plugin/blob/master/src/index.js#L492 this JSON.parse will fail since there is some warnings and becomes not valid JSON. then the build process always break and show error. even there is only some warnings.
I tried to create source map with webpack config devtool: 'source-map'
, since directly using the create_source_map
option of closure compiler is not recommended. However the path to source files in the source map file seems wrong.
For example, when I compile the mixed-module
demo, the source map looks like:
{
"version": 3,
"sources": [
"webpack:///main.js",
"webpack:///./node_modules/google-closure-library/closure/goog/math/Users/jing/Documents/js/webpack-demo/node_modules/google-closure-library/closure/goog/math/math.js",
"webpack:///./node_modules/object-assign/Users/jing/Documents/js/webpack-demo/node_modules/object-assign/index.js",
"webpack:///./node_modules/google-closure-library/closure/goog/array/Users/jing/Documents/js/webpack-demo/node_modules/google-closure-library/closure/goog/array/array.js",
"webpack:///./node_modules/google-closure-library/closure/goog/Users/jing/Documents/js/webpack-demo/node_modules/google-closure-library/closure/goog/base.js",
"webpack:///./src/Users/jing/Documents/js/webpack-demo/src/app.js",
"webpack:///./src/lib/Users/jing/Documents/js/webpack-demo/src/lib/esModule.js",
"webpack:///./src/lib/Users/jing/Documents/js/webpack-demo/src/lib/forwardEsModule.js",
"webpack:///./src/lib/Users/jing/Documents/js/webpack-demo/src/lib/googRequire.js",
"webpack:///./src/lib/Users/jing/Documents/js/webpack-demo/src/lib/googModule.js"
],
//...
}
Meanwhile, if I compile it with closure compiler CLI directly, the source map looks like:
{
"version": 3,
"file": "dist/bundle.js",
"lineCount": 2,
"sources": [
"../node_modules/object-assign/index.js",
"../node_modules/google-closure-library/closure/goog/array/array.js",
"../node_modules/google-closure-library/closure/goog/base.js",
"../node_modules/google-closure-library/closure/goog/math/math.js",
"../src/app.js",
"../src/lib/esModule.js",
"../src/lib/forwardEsModule.js",
"../src/lib/googRequire.js",
"../src/lib/googModule.js"
],
//...
which is correct.
Is this an issue with closure plugin or did I miss some options?
Package version:
webpack 3.12.0
closure-webpack-plugin 1.1.1
node v11.1.0
https://github.com/webpack-contrib/closure-webpack-plugin#closure-library-plugin
new ClosurePlugin.ClosureLibrary // error
new ClosurePlugin.LibraryPlugin // correct
When js file contains import css file;
Then google-closure-compiler will report error:
closure-compiler: Failed to load module "!!../node_modules/css-loader/index.js!./override.css" var newContent = require("!!../node_modules/css-loader/index.js!./override.css");
CCWP Plugin: v0.0.2
webpack by default when lazy loading is not used, will exclude the lazy loading jsonP and other template declarations. This makes for a smaller runtime bundle.
When I pretty printed out the code generated for CCWPP, I noticed it was still included. Not sure if this is possible or not, but wanted to throw a heads up at this optimization.
Here's the generated code in question: (PS there was no import() in the source).
bundle.js
(function(__wpcc){'use strict';
var d = d || {};
d.scope = {};
d.ASSUME_ES5 = !1;
d.ASSUME_NO_NATIVE_MAP = !1;
d.ASSUME_NO_NATIVE_SET = !1;
d.defineProperty = d.ASSUME_ES5 || "function" == typeof Object.defineProperties ? Object.defineProperty : function(a, b, c) {
a != Array.prototype && a != Object.prototype && (a[b] = c.value);
};
d.getGlobal = function(a) {
return "undefined" != typeof window && window === a ? a : "undefined" != typeof window.global && null != window.global ? window.global : a;
};
d.global = d.getGlobal(this);
d.SYMBOL_PREFIX = "jscomp_symbol_";
d.initSymbol = function() {
d.initSymbol = function() {
};
d.global.Symbol || (d.global.Symbol = d.Symbol);
};
d.Symbol = function() {
var a = 0;
return function(b) {
return d.SYMBOL_PREFIX + (b || "") + a++;
};
}();
d.initSymbolIterator = function() {
d.initSymbol();
var a = d.global.Symbol.iterator;
a || (a = d.global.Symbol.iterator = d.global.Symbol("iterator"));
"function" != typeof Array.prototype[a] && d.defineProperty(Array.prototype, a, {configurable:!0, writable:!0, value:function() {
return d.arrayIterator(this);
}});
d.initSymbolIterator = function() {
};
};
d.arrayIterator = function(a) {
var b = 0;
return d.iteratorPrototype(function() {
return b < a.length ? {done:!1, value:a[b++]} : {done:!0};
});
};
d.iteratorPrototype = function(a) {
d.initSymbolIterator();
a = {next:a};
a[d.global.Symbol.iterator] = function() {
return this;
};
return a;
};
d.makeIterator = function(a) {
d.initSymbolIterator();
var b = a[window.Symbol.iterator];
return b ? b.call(a) : d.arrayIterator(a);
};
d.polyfill = function(a, b) {
if (b) {
var c = d.global;
a = a.split(".");
for (var f = 0; f < a.length - 1; f++) {
var k = a[f];
k in c || (c[k] = {});
c = c[k];
}
a = a[a.length - 1];
f = c[a];
b = b(f);
b != f && null != b && d.defineProperty(c, a, {configurable:!0, writable:!0, value:b});
}
};
d.FORCE_POLYFILL_PROMISE = !1;
d.polyfill("Promise", function(a) {
function b(e) {
this.state_ = 0;
this.result_ = void 0;
this.onSettledCallbacks_ = [];
var a = this.createResolveAndReject_();
try {
e(a.resolve, a.reject);
} catch (m) {
a.reject(m);
}
}
function c() {
this.batch_ = null;
}
function f(e) {
return e instanceof b ? e : new b(function(a) {
a(e);
});
}
if (a && !d.FORCE_POLYFILL_PROMISE) {
return a;
}
c.prototype.asyncExecute = function(e) {
null == this.batch_ && (this.batch_ = [], this.asyncExecuteBatch_());
this.batch_.push(e);
return this;
};
c.prototype.asyncExecuteBatch_ = function() {
var e = this;
this.asyncExecuteFunction(function() {
e.executeBatch_();
});
};
var k = d.global.setTimeout;
c.prototype.asyncExecuteFunction = function(e) {
k(e, 0);
};
c.prototype.executeBatch_ = function() {
for (; this.batch_ && this.batch_.length;) {
var e = this.batch_;
this.batch_ = [];
for (var a = 0; a < e.length; ++a) {
var b = e[a];
delete e[a];
try {
b();
} catch (n) {
this.asyncThrow_(n);
}
}
}
this.batch_ = null;
};
c.prototype.asyncThrow_ = function(a) {
this.asyncExecuteFunction(function() {
throw a;
});
};
b.prototype.createResolveAndReject_ = function() {
function a(a) {
return function(e) {
c || (c = !0, a.call(b, e));
};
}
var b = this, c = !1;
return {resolve:a(this.resolveTo_), reject:a(this.reject_)};
};
b.prototype.resolveTo_ = function(a) {
if (a === this) {
this.reject_(new TypeError("A Promise cannot resolve to itself"));
} else {
if (a instanceof b) {
this.settleSameAsPromise_(a);
} else {
a: {
switch(typeof a) {
case "object":
var e = null != a;
break a;
case "function":
e = !0;
break a;
default:
e = !1;
}
}
e ? this.resolveToNonPromiseObj_(a) : this.fulfill_(a);
}
}
};
b.prototype.resolveToNonPromiseObj_ = function(a) {
var b = void 0;
try {
b = a.then;
} catch (m) {
this.reject_(m);
return;
}
"function" == typeof b ? this.settleSameAsThenable_(b, a) : this.fulfill_(a);
};
b.prototype.reject_ = function(a) {
this.settle_(2, a);
};
b.prototype.fulfill_ = function(a) {
this.settle_(1, a);
};
b.prototype.settle_ = function(a, b) {
if (0 != this.state_) {
throw Error("Cannot settle(" + a + ", " + b | "): Promise already settled in state" + this.state_);
}
this.state_ = a;
this.result_ = b;
this.executeOnSettledCallbacks_();
};
b.prototype.executeOnSettledCallbacks_ = function() {
if (null != this.onSettledCallbacks_) {
for (var a = this.onSettledCallbacks_, b = 0; b < a.length; ++b) {
a[b].call(), a[b] = null;
}
this.onSettledCallbacks_ = null;
}
};
var g = new c;
b.prototype.settleSameAsPromise_ = function(a) {
var b = this.createResolveAndReject_();
a.callWhenSettled_(b.resolve, b.reject);
};
b.prototype.settleSameAsThenable_ = function(a, b) {
var e = this.createResolveAndReject_();
try {
a.call(b, e.resolve, e.reject);
} catch (n) {
e.reject(n);
}
};
b.prototype.then = function(a, c) {
function e(a, b) {
return "function" == typeof a ? function(b) {
try {
f(a(b));
} catch (p) {
l(p);
}
} : b;
}
var f, l, g = new b(function(a, b) {
f = a;
l = b;
});
this.callWhenSettled_(e(a, f), e(c, l));
return g;
};
b.prototype.catch = function(a) {
return this.then(void 0, a);
};
b.prototype.callWhenSettled_ = function(a, b) {
function e() {
switch(c.state_) {
case 1:
a(c.result_);
break;
case 2:
b(c.result_);
break;
default:
throw Error("Unexpected state: " + c.state_);
}
}
var c = this;
null == this.onSettledCallbacks_ ? g.asyncExecute(e) : this.onSettledCallbacks_.push(function() {
g.asyncExecute(e);
});
};
b.resolve = f;
b.reject = function(a) {
return new b(function(b, c) {
c(a);
});
};
b.race = function(a) {
return new b(function(b, c) {
for (var e = d.makeIterator(a), g = e.next(); !g.done; g = e.next()) {
f(g.value).callWhenSettled_(b, c);
}
});
};
b.all = function(a) {
var c = d.makeIterator(a), e = c.next();
return e.done ? f([]) : new b(function(a, b) {
function g(b) {
return function(c) {
k[b] = c;
l--;
0 == l && a(k);
};
}
var k = [], l = 0;
do {
k.push(void 0), l++, f(e.value).callWhenSettled_(g(k.length - 1), b), e = c.next();
} while (!e.done);
});
};
return b;
}, "es6", "es3");
var h, q = this;
"undefined" === typeof h && (h = function() {
});
h.c = h.c || {};
(function() {
var a = window.webpackJsonp;
window.webpackJsonp = function(b, c) {
var f = 0, k = [];
for (c.call(q, __wpcc); f < b.length; f++) {
c = b[f], h.c[c] && k.push(h.c[c][0]), h.c[c] = 0;
}
for (a && a(b, function() {
}); k.length;) {
k.shift()();
}
};
})();
h.e = function(a) {
function b() {
g.onerror = g.onload = null;
(0,window.clearTimeout)(e);
var b = h.c[a];
if (0 !== b) {
if (b) {
b[1](Error("Loading chunk " + a + " failed."));
}
h.c[a] = void 0;
}
}
var c = h.c[a];
if (0 === c) {
return new window.Promise(function(a) {
a();
});
}
if (c) {
return c[2];
}
var f = new window.Promise(function(b, e) {
c = h.c[a] = [b, e];
});
c[2] = f;
var k = window.document.getElementsByTagName("head")[0], g = window.document.createElement("script");
g.type = "text/javascript";
g.charset = "utf-8";
g.async = !0;
g.timeout = 120000;
0 < h.nc.length && g.setAttribute("nonce", h.nc);
g.src = h.src(a);
var e = (0,window.setTimeout)(b, h.to);
g.onerror = g.onload = b;
k.appendChild(g);
return f;
};
h.p = "";
h.nc = "";
h.to = 120000;
h.oe = function(a) {
window.console.error(a);
throw a;
};
h.src = function(a) {
return h.p + "" + a + ".bundle.js";
};
}).call(this, {});
webpackJsonp([0], function(__wpcc){'use strict';
window.console.log("other message");
});
Need to be able to calculate the full runtime path to a chunk being loaded using the hash and length. Right now, you basically need to not use hashes in the filenames.
I'm having a hard time building simple Javascript files. For example, assume that my entry point is in src/app.js
and the contents are:
goog.provide('myapp.module');
goog.scope(function () {
myapp.module = function() {
return 3+3;
}
});
I get the following error:
The call to goog.scope must be in the global scope.
And if, for example, the contents are:
goog.require("goog.crypt.Sha1");
var sha1 = new goog.crypt.Sha1();
sha1.update("foobar");
var hash = sha1.digest();
I get the following error:
Closure dependency methods(goog.provide, goog.require, etc) must be called at file scope.
I have no idea what's going on and I've been stuck on it for a couple days now. Is Webpack doing something funky w/ the scope? Any leads would be very helpful! Thanks
Adding the plugin throws errors and there is no example or direction for a configuration. From the code, it appears that the entryChunk remains undefined on index.js line 138
const entryChunk = originalChunks.find(chunk => chunk.hasEntryModule() && chunk.hasRuntime());
Is there additional configuration required? What is the assumed tsconfig?
I am approaching the build from the point of ejecting a webpack build from the Angular CLI
A webpac.config.js generated by the CLI eject function does not define the entry module in the tsconfig or the ngtools AngularCompilerPlugin options. There is no way to know what is being assumed here?
Error:
const chunkMaps = entryChunk.getChunkMaps();
^
TypeError: Cannot read property 'getChunkMaps' of undefined
at ClosureCompilerPlugin.aggressiveBundle (C:\P4\OrganizedPlay\main\web\node_modules\closure-webpack-plugin\src\index.js:138:34)
Angular 5.0.1
Angular CLI 1.6.0-beta.0
Webpack 3.8.1
Windows 10
Node 8.9.0
npm 5.5.1
"webpack": "^4.26.1",
"closure-webpack-plugin": "^2.0.0-rc.1",
It seems that this feature should be implemented in the compiler, how should I solve it?
google/closure-compiler@467c4ed
Logic in https://github.com/webpack-contrib/closure-webpack-plugin/blob/master/src/index.js#L73 is not very correct. Main build also can be easily named with name
field.
It should be specified somewhere in docs or just be in issues here.
I spend several hours to figure it out :)
The java version of closure compiler accepts extra command arguments:
// closure-compiler.js
class Compiler {
/**
* @param {Object<string,string>|Array<string>} args
* @param {Array<String>=} extraCommandArgs
*/
constructor(args, extraCommandArgs) {
//...
For example, if I pass ['-Xmx2g', '-Xss8m']
, the command being executed will be:
java -Xmx2g -Xss8m -jar compiler.jar ...
This is useful to prevent OOM problem or improve compilation time during CI build.
I propose adding a flag extraCommandArgs
in closure plugin, and pass it as the second argument to compiler:
new ClosurePlugin({mode: 'STANDARD'}, {
// compiler flags
extraCommandArgs: [
'-Xmx2g',
'-Xss8m'
]
})
If it's reasonable, I can submit a PR.
Hi guys,
I have an issue with a multi-module build (I'm talking about output modules here related to code splitting and --module
flag).
Here's my webpack config:
var path = require('path');
var webpack = require('webpack');
var ClosurePlugin = require("closure-webpack-plugin");
module.exports = {
context: path.resolve(__dirname),
entry: {
'module1': './module1.js',
'module2': './module2.js',
},
output: {
filename: '[name].build.js',
path: path.resolve(__dirname, '../www/js')
},
plugins: [
new ClosurePlugin({
mode: 'AGGRESSIVE_BUNDLE',
closureLibraryBase: require.resolve('google-closure-library/closure/goog/base'),
deps: [
path.resolve(__dirname, './my-deps.js')
]
}, {
compilation_level: 'WHITESPACE_ONLY',
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'module1',
minChunks: 2
})
]
};
module1.js:
goog.provide('module1');
console.info('module1');
module2.js:
goog.provide('module2');
goog.require('module1');
console.info('module2');
Here's the output generated into module2.build.js
:
webpackJsonp([0], function(__wpcc){'use strict';goog.provide("module2");goog.require("module1");console.info("module2");});
The problem is the inner function is never called.
When both module1.build.js
and module2.build.js
are linked to the page, I only see module1
string in the console output.
There's no module2
string.
This behaviour is reproducible for any number of modules more than 1 and any compilation_level
.
On the other hand, if I comment out ClosurePlugin
in the config, both modules run when loaded.
Here's module2.build.js
in this case:
webpackJsonp([1],[
/* 0 */,
/* 1 */
/***/ (function(module, exports) {
goog.provide('module2');
goog.require('module1');
console.info('module2');
/***/ })
],[1]);
For this one I see both module1
and module2
strings in the console output.
This example covers only a case with 1 output module.
I feel like it's not an intended behaviour, that's why opened this issue.
I have node v8.9.4 on OSX 10.12.6.
I've been trying for a couple of days to get closure-webpack-plugin integrated with a larger software project, but was hitting lots of compilation errors and trying lots of fixes but could not get the project to compile.
So I decided to clone the example project (mixed-modules
) from this repo and at least get that compiling and work from there to fix my problem.
However I am seeing many of the same error messages while trying to compile the example project.
Out of the box, simply cloning the project, installing the dependencies, and running npm run build
(npm production mode, compiler using AGGRESSIVE_BUNDLE mode as per the example)
gives these errors
$ run-s build:deps build:webpack
$ ./node_modules/google-closure-deps/bin/closuremakedeps.js --no-validate --root src --closure-path './node_modules/google-closure-library/closure/goog' > public/deps.js
$ webpack -p --env production
undefined
Hash: f4bacb23c5a30a9f4c35
Version: webpack 3.12.0
Time: 626ms
Asset Size Chunks Chunk Names
app.js 228 kB 0 [emitted] app
[1] ./src/lib/esModule.js 152 bytes {0} [built]
[3] ./src/app.js 704 bytes {0} [built]
[9] ./src/lib/googRequire.js 98 bytes {0} [built]
[10] ./src/lib/googModule.js 87 bytes {0} [built]
[11] ./src/lib/forwardEsModule.js 144 bytes {0} [built]
+ 7 hidden modules
ERROR in ./src/app.js:9 (originally at ./src//home/user/projects/mixed-modules/src/app.js:7) from closure-compiler: Closure dependency methods(goog.provide, goog.require, etc) must be called at file scope.
const math = goog.require('goog.math');
^^^^^^^^^^^^^^^^^^^^^^^^^
ERROR in ./src/app.js:12 (originally at ./src//home/user/projects/mixed-modules/src/app.js:10) from closure-compiler: Closure dependency methods(goog.provide, goog.require, etc) must be called at file scope.
const googRequire = goog.require('app.googRequire');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ERROR in ./src/app.js:15 (originally at ./src//home/user/projects/mixed-modules/src/app.js:13) from closure-compiler: Closure dependency methods(goog.provide, goog.require, etc) must be called at file scope.
const googModule = goog.require('app.googModule');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ERROR in ./src/app.js:18 (originally at ./src//home/user/projects/mixed-modules/src/app.js:16) from closure-compiler: Closure dependency methods(goog.provide, goog.require, etc) must be called at file scope.
const forwardEsModule = goog.require('app.forwardEsModule');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ERROR in app.js from UglifyJs
Unexpected token: keyword (default) [app.js:4016,7]
error Command failed with exit code 2.
Then when changing from AGGRESSIVE_BUNDLE to STANDARD mode, and running npm run build
again, I get a similar message:
$ run-s build:deps build:webpack
$ ./node_modules/google-closure-deps/bin/closuremakedeps.js --no-validate --root src --closure-path './node_modules/google-closure-library/closure/goog' > public/deps.js
$ webpack -p --env production
undefined
Hash: f4bacb23c5a30a9f4c35
Version: webpack 3.12.0
Time: 971ms
Asset Size Chunks Chunk Names
app.js 52.7 kB 0 [emitted] app
[1] ./src/lib/esModule.js 152 bytes {0} [built]
[3] ./src/app.js 704 bytes {0} [built]
[9] ./src/lib/googRequire.js 98 bytes {0} [built]
[10] ./src/lib/googModule.js 87 bytes {0} [built]
[11] ./src/lib/forwardEsModule.js 144 bytes {0} [built]
+ 7 hidden modules
WARNING in closure-compiler: File cannot be a combination of goog.provide, goog.module, and/or ES6 module: app.js
ERROR in app.js:6838 (originally at ./src/lib/googModule.js:1) from closure-compiler: A file cannot be both a goog.provide'd file and a goog.module.
goog.module('app.googModule');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ERROR in app.js:6849 (originally at ./src/lib/forwardEsModule.js:1) from closure-compiler: A file cannot be both a goog.provide'd file and a goog.module.
goog.module('app.forwardEsModule');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error Command failed with exit code 2.
Using package versions:
webpack: 3.12.0
closure-webpack-plugin: 1.1.1
google-closure-compiler: 20180805.0.0 (also tried with 20181008.0.0)
google-closure-deps: 20180910.1.0
google-closure-library: 20180505.0.0
Node version: v8.12.0
NPM version: v6.4.1, also tried with yarn instead of NPM.
Closure-compiler-platform: linux native
Is there anything obvious I'm doing wrong?
The error messages seem obvious to me, webpack is bundling all of the source into one file (app.js) and the compiler chokes on that because it cannot have goog.provide and goog.module in the same file. How is the closure-webpack-plugin normally supposed to work around that?
Currently the options provided to the plugin are passed directly to the compiler as flags. Refactor the options to support configuration of the plugin itself.
Plan is to support 2 modes:
In either mode, need to support specifying compiler flags as well.
Using package versions:
closure-webpack-plugin: 2.0.0
webpack: 4.29.6
webpack-dev-server: 3.2.1
google-closure-library: 20190121.0.0
google-closure-compiler: 20190215.0.1
node: 11.10.1
npm: 6.8.0
platform: ubuntu 18.04 LTS
JDK: 1.8.0_201
Example:
// app.js
import './empty';
const math = goog.require('goog.math');
console.log(math.average(10, 20, 30, 40));
// empty.js
// just a empty js file
// webpack.config.js
const path = require('path');
const ClosureWebplugPlugin = require('closure-webpack-plugin');
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production' || !argv.mode;
return {
entry: {
app: './src/app.js',
},
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].js',
},
devServer: {
contentBase: path.resolve(__dirname, 'build')
},
devtool: 'source-map',
optimization: {
minimize: isProduction,
minimizer: [
new ClosureWebplugPlugin({
mode: 'AGGRESSIVE_BUNDLE'
}, {
compilation_level: 'ADVANCED'
})
],
splitChunks: {
minSize: 0
},
concatenateModules: false,
},
plugins: [
new ClosureWebplugPlugin.LibraryPlugin(
{
closureLibraryBase: require.resolve('google-closure-library/closure/goog/base'),
deps: [
require.resolve('google-closure-library/closure/goog/deps'),
'./src/deps.js',
],
})
]
};
};
I wrote a very simple demo. When I try to build it with 'AGGRESSIVE_BUNDLE' option, it works fine, but after I add 'compilation_level: "ADVANCED"' flag, it will appear a ERROR like this:
ERROR in closure-compiler: java.lang.IllegalArgumentException: expected one element but was: <required-base, app>
at java.lang.Throwable.<init>(Throwable.java:265)
at java.lang.Exception.<init>(Exception.java:66)
at java.lang.RuntimeException.<init>(RuntimeException.java:62)
at java.lang.IllegalArgumentException.<init>(IllegalArgumentException.java:52)
at com.google.common.collect.Iterators.getOnlyElement(Iterators.java:316)
at com.google.common.collect.Iterables.getOnlyElement(Iterables.java:254)
at com.google.javascript.jscomp.JSModuleGraph.getRootModule(JSModuleGraph.java:307)
at com.google.javascript.jscomp.AnalyzePrototypeProperties.<init>(AnalyzePrototypeProperties.java:125)
at com.google.javascript.jscomp.CrossChunkMethodMotion.<init>(CrossChunkMethodMotion.java:87)
at com.google.javascript.jscomp.DefaultPassConfig$89.create(DefaultPassConfig.java:2730)
at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:328)
at com.google.javascript.jscomp.PhaseOptimizer$Loop.process(PhaseOptimizer.java:473)
at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:237)
at com.google.javascript.jscomp.Compiler.performOptimizations(Compiler.java:2368)
at com.google.javascript.jscomp.Compiler.lambda$stage2Passes$1(Compiler.java:782)
at com.google.javascript.jscomp.Compiler$$Lambda$363/395995234.call(Unknown Source)
at com.google.javascript.jscomp.CompilerExecutor$2.call(CompilerExecutor.java:102)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:475)
at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:199)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.