I am new to webpack and next.js. I get the following error, that seems webpack does not understand/parse/load CSS files correctly.
C:\devtmp\workspaces\nextjs\web-admin\node_modules\#patternfly\react-styles\css\components\Backdrop\backdrop.css:4
.pf-c-backdrop {
^
SyntaxError: Unexpected token .
How can I fix this or debug this further? As I am new, I am completely lost. What could be the cause for this problem?
Further Details:
1.) Full Stacktrace:
[ info ] bundled successfully, waiting for typecheck results ...
[ event ] build page: /test
[ wait ] compiling ...
[ info ] bundled successfully, waiting for typecheck results ...
[ ready ] compiled successfully - ready on http://localhost:3000
C:\devtmp\workspaces\nextjs\web-admin\node_modules\#patternfly\react-styles\css\components\Backdrop\backdrop.css:4
.pf-c-backdrop {
^
SyntaxError: Unexpected token .
at Module._compile (internal/modules/cjs/loader.js:720:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Module.require (internal/modules/cjs/loader.js:683:19)
at require (internal/modules/cjs/helpers.js:16:16)
at Object.<anonymous> (C:\devtmp\workspaces\nextjs\web-admin\node_modules\#patternfly\react-styles\css\components\Backdrop\backdrop.js:3:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Module.require (internal/modules/cjs/loader.js:683:19)
at require (internal/modules/cjs/helpers.js:16:16)
at Object.<anonymous> (C:\devtmp\workspaces\nextjs\web-admin\node_modules\#patternfly\react-core\dist\js\components\AboutModal\AboutModal.js:16:40)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
2.) The File that does the CSS import
file:///C:/devtmp/workspaces/nextjs/web-admin/node_modules/#patternfly/react-styles/css/components/Backdrop/backdrop.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("./backdrop.css");
exports.default = {
backdrop: 'pf-c-backdrop',
backdropOpen: 'pf-c-backdrop__open',
modifiers: {}
};
3.) The CSS
file:///C:/devtmp/workspaces/nextjs/web-admin/node_modules/#patternfly/react-styles/css/components/Backdrop/backdrop.css
/* stylelint-enable */
/* stylelint-disable */
/* stylelint-enable */
.pf-c-backdrop {
--pf-c-backdrop--ZIndex: var(--pf-global--ZIndex--lg);
--pf-c-backdrop--Color: var(--pf-global--BackgroundColor--dark-transparent-100);
--pf-c-backdrop--BackdropFilter: blur(10px);
position: fixed;
top: 0;
left: 0;
z-index: var(--pf-c-backdrop--ZIndex);
width: 100%;
height: 100%;
background-color: var(--pf-c-backdrop--Color);
/* stylelint-disable-next-line */
-webkit-backdrop-filter: var(--pf-c-backdrop--BackdropFilter);
backdrop-filter: var(--pf-c-backdrop--BackdropFilter); }
.pf-c-backdrop__open {
overflow: hidden; }
4.) Extract of next.config.js
module.exports = {
webpack: (config, options) => {
config.module.rules.push({
test: /\.css$/,
//exclude: ['/node_modules/'],
include: [
path.resolve(__dirname, 'pages'),
path.resolve(__dirname, 'node_modules/patternfly'),
path.resolve(__dirname, 'node_modules/#patternfly/patternfly'),
path.resolve(__dirname, 'node_modules/#patternfly/react-styles/css'),
path.resolve(__dirname, 'node_modules/#patternfly/react-core/dist/styles/base.css'),
path.resolve(__dirname, 'node_modules/#patternfly/react-core/dist/esm/#patternfly/patternfly'),
path.resolve(__dirname, 'node_modules/#patternfly/react-core/node_modules/#patternfly/react-styles/css'),
path.resolve(__dirname, 'node_modules/#patternfly/react-table/node_modules/#patternfly/react-styles/css'),
path.resolve(__dirname, 'node_modules/#patternfly/react-inline-edit-extension/node_modules/#patternfly/react-styles/css')
],
use: ["style-loader", "css-loader"]
});
...
Thanks very much!
As of the fact that next provide a solution for ssr & client side it has 2 webpack configs, one for each.
Instead of configuring it by yourself it is better to use the official (for now) plugin #zeit/next-css.
// next.config.js
const withCSS = require('#zeit/next-css')
module.exports = withCSS()
WARN Edit: 06-07-2021
This package has been deprecated
Author message:
Next.js now has built-in support for CSS: https://nextjs.org/docs/basic-features/built-in-css-support. The built-in support solves many bugs and painpoints that the next-css plugin had.
Related
I must be missing something but I'm struggling to understand this error.
How can . be unexpected in module.exports={}?
Please point me in the right direction. Thanks!
\jest.config.js:16
module.exports = {
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at readConfigFileAndSetRootDir (...\node_modules\jest-config\build\readConfigFileAndSetRootDir.js:119:22)
at readConfig (...\node_modules\jest-config\build\index.js:217:65)
at readConfigs (...\node_modules\jest-config\build\index.js:406:32)
npm ERR! Test failed. See above for more details.
jest.config.js:
module.exports = {
transform: {
"^.+\\.[jt]sx?$": "<rootDir>/jest-preprocess.js",
},
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`,
},
testPathIgnorePatterns: [`node_modules`, `\\.cache`, `<rootDir>.*/public`],
transformIgnorePatterns: [`node_modules/(?!(gatsby)/)`],
globals: {
__PATH_PREFIX__: ``,
},
testURL: `http://localhost`,
setupFiles: [`<rootDir>/loadershim.js`],
module.exports = {
setupFilesAfterEnv: ["<rootDir>/setup-test-env.js"],
}
};
You have an extra module.exports embedded in the object at the bottom. looks like the file should be:
module.exports = {
transform: {
"^.+\\.[jt]sx?$": "<rootDir>/jest-preprocess.js",
},
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`,
},
testPathIgnorePatterns: [`node_modules`, `\\.cache`, `<rootDir>.*/public`],
transformIgnorePatterns: [`node_modules/(?!(gatsby)/)`],
globals: {
__PATH_PREFIX__: ``,
},
testURL: `http://localhost`,
setupFiles: [`<rootDir>/loadershim.js`],
setupFilesAfterEnv: ["<rootDir>/setup-test-env.js"],
};
I solved this during the writing of the question and have provided my answer below since it was a bit tricky to work out. I am happy to hear any better or alternative answers.
I have an Angular OpenLayers 6 geomapping app. Being Angular I use Typescript and it transpiles and runs fine. And also being Angular it uses ng test to do the testing. All tests run fine.
However I use mocha + chai for testing in the IDE (IntelliJ) since I don't require UI testing for the mathematical work I'm currently performing (ng test runs the UI tests if and when I need that. But in the IDE I select the tests to run). Testing this way worked fine until I added a new test that creates a new instance of a class that imports GeoJSON:
import GeoJSON from 'ol/format/GeoJSON';
That test fails (in mocha) with:
/home/smx9b6/dev/ng-eow/node_modules/ol/format/GeoJSON.js:17
import { assert } from '../asserts.js';
^
SyntaxError: Unexpected token {
Looking at the GeoJSON.js file it seems to have UMD module format (i think this is UMD):
/**
* #module ol/format/GeoJSON
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { assert } from '../asserts.js';
import Feature from '../Feature.js';
var GeoJSON = /** #class */ (function (_super) {
__extends(GeoJSON, _super);
/**
* #param {Options=} opt_options Options.
*/
function GeoJSON(opt_options) {
...
}
GeoJSON.prototype.writeGeometryObject = function (geometry, opt_options) {
return writeGeometry(geometry, this.adaptOptions(opt_options));
};
return GeoJSON;
}(JSONFeature));
And others, such as turf.js use the ES6 module format. eg. line-to-polygon:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bbox_1 = require("#turf/bbox");
var invariant_1 = require("#turf/invariant");
var helpers_1 = require("#turf/helpers");
...
function lineToPolygon(lines, options) {
if (options === void 0) { options = {}; }
...
}
...
exports.default = lineToPolygon;
Mocha can't deal with this but Angular can - I don't know why. I run mocha with (as reported by IntelliJ when running the test - full paths removed):
node node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter mochaIntellijReporter.js
src/app/geometry-ops.spec.ts --grep "^geometry-ops centroid "
I have commonjs set as the module type:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"resolveJsonModule": true,
"module": "commonjs",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
...
}
The error in full is:
/home/smx9b6/dev/ng-eow/node_modules/ol/format/GeoJSON.js:17
import { assert } from '../asserts.js';
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/home/smx9b6/dev/ng-eow/src/app/layers-geometries.ts:4:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Module.m._compile (/home/smx9b6/dev/ng-eow/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/smx9b6/dev/ng-eow/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/home/smx9b6/dev/ng-eow/src/app/geometry-ops.spec.ts:13:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Module.m._compile (/home/smx9b6/dev/ng-eow/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/smx9b6/dev/ng-eow/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at /home/smx9b6/dev/ng-eow/node_modules/mocha/lib/mocha.js:334:36
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/home/smx9b6/dev/ng-eow/node_modules/mocha/lib/mocha.js:331:14)
at Mocha.run (/home/smx9b6/dev/ng-eow/node_modules/mocha/lib/mocha.js:809:10)
at Object.exports.singleRun (/home/smx9b6/dev/ng-eow/node_modules/mocha/lib/cli/run-helpers.js:108:16)
at exports.runMocha (/home/smx9b6/dev/ng-eow/node_modules/mocha/lib/cli/run-helpers.js:142:13)
at Object.exports.handler.argv [as handler] (/home/smx9b6/dev/ng-eow/node_modules/mocha/lib/cli/run.js:292:3)
at Object.runCommand (/home/smx9b6/dev/ng-eow/node_modules/mocha/node_modules/yargs/lib/command.js:242:26)
at Object.parseArgs [as _parseArgs] (/home/smx9b6/dev/ng-eow/node_modules/mocha/node_modules/yargs/yargs.js:1087:28)
at Object.parse (/home/smx9b6/dev/ng-eow/node_modules/mocha/node_modules/yargs/yargs.js:566:25)
at Object.exports.main (/home/smx9b6/dev/ng-eow/node_modules/mocha/lib/cli/cli.js:68:6)
at Object.<anonymous> (/home/smx9b6/dev/ng-eow/node_modules/mocha/bin/_mocha:10:23)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
I worked out and provide an answer below. However I would still like to hear any feedback on this. Such as should OpenLayers change their module format? (I'm still getting my head around all the different module formats).
The answer is to add --require esm --require jsdom-global/register to the node / mocha call.
The esm is to specify ES6 as the module format and jsdom-global is to define the DOM in non-browser environments (specifically to define document).
The full command is:
node node_modules/mocha/bin/_mocha --ui bdd \
--require ts-node/register \
--require esm \
--require jsdom-global/register \
--reporter landing \
src/app/geometry-ops.spec.ts --grep "^geometry-ops centroid "
(I added spaces in the command since it irks me when I have to scroll right to see such things).
I am happy to hear any better or alternative answers.
Im trying to add gulp-eslint to my build process, having gulp watch my files and run eslint whenever a file is changed. However, I am getting an error that says:
D:\code\project\node_modules\gulp-eslint\index.js:4
const {CLIEngine} = require('eslint');
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (D:\code\project\gulpfile.js:5:16)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
when I try to run the ESLint task that I wrote.
Here is the code for the eslint task:
gulp.task('eslint', () => {
return gulp.src(lintscripts)
.pipe(eslint({
"env": {
"browser": true,
"node": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2017
},
"rules": {
'no-console': 'off',
'indent' : 'off',
"semi": [
"error",
"always"
]
}
})).pipe(eslint.format());
});
Please check your node version. You are using object destructuring which is available from Node v6. If you're using node v4 then this might not work.
I am fairly new when it comes to modern web development paradigms.
I have recently read this article to get myself up to speed.
https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70
and am currently trying to implement the tutorial in this article
https://codeburst.io/how-to-use-webpack-in-asp-net-core-projects-a-basic-react-template-sample-25a3681a5fc2
Both are from 2017 and there have been apparently large syntactical changes to webpack since then. I was wondering if someone could help explain why I get this error
PS C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact> npm run build:dev
> ASPNetCoreReact#1.0.0 build:dev C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact
> webpack --mode=development
C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\webpack.config.js:23
{ test: /\.css$/, use: extractCSS.extract(['css-loader?
^^^^^^^^^^^^
SyntaxError: Invalid or unexpected token
at new Script (vm.js:80:7)
at NativeCompileCache._moduleCompile (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\v8-compile-cache\v8-compile-cache.js:226:18)
at Module._compile (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\v8-compile-cache\v8-compile-cache.js:172:36)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
at WEBPACK_OPTIONS (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\utils\convert-argv.js:115:13)
at requireConfig (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\utils\convert-argv.js:117:6)
at C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\utils\convert-argv.js:124:17
at Array.forEach (<anonymous>)
at module.exports (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\utils\convert-argv.js:122:15)
at yargs.parse (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\cli.js:71:45)
at Object.parse (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\yargs\yargs.js:567:18)
at C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\cli.js:49:8
at Object.<anonymous> (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack-cli\bin\cli.js:368:3)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (C:\Users\sgibson\source\repos\ASPNetCoreReact\ASPNetCoreReact\node_modules\webpack\bin\webpack.js:156:2)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ASPNetCoreReact#1.0.0 build:dev: `webpack --mode=development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ASPNetCoreReact#1.0.0 build:dev script.
When utilizing this webpack.config.
module.exports = {
entry: "./wwwroot/source/app.js",
output: {
path: path.resolve(__dirname, "wwwroot/dist"),
filename: "bundle.js"
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
Popper: ["popper.js", "default"]
}),
new webpack.optimize.UglifyJsPlugin()
],
module: {
rules: [
{ test: /\.css$/, use: extractCSS.extract(["css-loader?minimize"]) },
{
test: /\.js?$/,
use: {
loader: "babel-loader",
options: { presets: ["#babel/preset-env"] }
}
}
]
}
};
Webpack syntax is very confusing to me. I don't really follow the flow that is happening here.
I figured out the answer to my question. My apologies for not giving myself a little more time to dive deeper. I was just feeling really lost. I needed to read up on each individual component in the webpack file to figure out how they should be interacting/declared in 2019 versus in the versions they were in 2017.
This ended up clearing all of the errors out
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('allstyles.css');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
optimization: {
minimizer: [new UglifyJsPlugin()],
},
entry: './wwwroot/source/app.js',
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: 'bundle.js'
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
}),
],
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.js?$/,
use: {
loader: 'babel-loader', options: {
presets:
['#babel/preset-env']
}
}
},
]
}
};
I am struggling setting up a Node project with TypeScript.
My workflow is: I run a Node script using nodemon. The node script creates a webpack compiler instance and sets the filesystem to MemoryFS. The webpack config includes loaders for TypeScript and Babel.
After webpack has finished compiling, if there are errors, I throw then, if not I fetch the result with MemoryFS and eval() it to run the code.
All of that works fine. But I tried to add sourcemaps support. I added a banner plugin in webpack which adds 'source-map-support'. In webpack, I set the devtool to 'source-map'. In tsconfig.json, I have the sourcemaps option enabled. In the src/index.ts I just throw an error, and at runtime Node doesn't tell me where did the error occur. (the sourcemap)
But if I run webpack normally, and then I run it using node dist/bundle.js. It is working.
I think there is a problem because of me using eval() to run the compiled output.
src/index.ts:
console.log('Hello world');
throw new Error('not');
build.js:
const path = require('path');
const webpack = require('webpack');
const MemoryFS = require('memory-fs');
const fs = new MemoryFS();
const config = require('./webpack.config');
const compiler = webpack(config);
compiler.outputFileSystem = fs;
compiler.run((err, stats) => {
console.clear();
const jsonStats = stats.toJson();
if(jsonStats.errors.length > 0 || jsonStats.warnings.length > 0)
return console.log(jsonStats.warning, jsonStats.errors);
const result = fs.readFileSync(path.resolve(__dirname, 'dist', 'bundle.js')).toString();
eval(result);
});
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const SRC_DIR = path.resolve(__dirname, 'src');
const DIST_DIR = path.resolve(__dirname, 'dist');
module.exports = {
entry: SRC_DIR + '/index.ts',
output: {
path: DIST_DIR,
filename: 'bundle.js'
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader'
},
{
test: /\.ts$/,
use: [
{ loader: 'babel-loader' },
{ loader: 'ts-loader' },
{ loader: 'tslint-loader' }
]
}
]
},
resolve: {
extensions: ['.ts', '.js', '.json']
},
target: 'node',
plugins: [
new webpack.BannerPlugin({
raw: true,
entryOnly: false,
banner: 'require("source-map-support").install();'
}),
new webpack.NoEmitOnErrorsPlugin()
]
};
After running webpack normally and executing the code (webpack && node dist\bundle.js, as expected):
C:\Users\shachar\Desktop\graph\dist\webpack:\src\index.ts:3
throw new Error('not');
^
Error: not
at Object.<anonymous> (C:\Users\shachar\Desktop\graph\dist\webpack:\src\index.ts:3:7)
at __webpack_require__ (C:\Users\shachar\Desktop\graph\dist\webpack:\webpack\bootstrap a6ba0885ca7e8b14ee63:19:1)
at C:\Users\shachar\Desktop\graph\dist\webpack:\webpack\bootstrap a6ba0885ca7e8b14ee63:62:1
at Object.<anonymous> (C:\Users\shachar\Desktop\graph\dist\bundle.js:67:10)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
Running it using build.js:
Hello world
Error: not
at Object.eval (eval at compiler.run (C:\Users\shachar\Desktop\graph\build.js:23:5), <anonymous>:75:7)
at __webpack_require__ (eval at compiler.run (C:\Users\shachar\Desktop\graph\build.js:23:5), <anonymous>:21:30)
at eval (eval at compiler.run (C:\Users\shachar\Desktop\graph\build.js:23:5), <anonymous>:64:18)
at eval (eval at compiler.run (C:\Users\shachar\Desktop\graph\build.js:23:5), <anonymous>:67:10)
at compiler.run (C:\Users\shachar\Desktop\graph\build.js:23:5)
at emitRecords.err (C:\Users\shachar\Desktop\graph\node_modules\webpack\lib\Compiler.js:269:13)
at Compiler.emitRecords (C:\Users\shachar\Desktop\graph\node_modules\webpack\lib\Compiler.js:375:38)
at emitAssets.err (C:\Users\shachar\Desktop\graph\node_modules\webpack\lib\Compiler.js:262:10)
at applyPluginsAsyncSeries1.err (C:\Users\shachar\Desktop\graph\node_modules\webpack\lib\Compiler.js:368:12)
at next (C:\Users\shachar\Desktop\graph\node_modules\tapable\lib\Tapable.js:218:11)
Thanks for any help!
When you use eval to run the code, Node will have no idea about the source map. Perhaps you can try to run a child node process instead of using eval to run the result, or is there any reason you're using eval? See https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback