VM2 Usage with Webpack - javascript

I've been having trouble using webpack with a typescript project that uses vm2.webpack --config webpack.config.js gives the following error:
ERROR in index.js from Terser
Invalid function parameter [webpack://./node_modules/source-map-loader/dist/cjs.js!./node_modules/vm2/lib/main.js:1226,1][index.js:1262,21]
This is the minimal repro I've been testing with:
import { VM } from 'vm2';
export async function run(): Promise<void> {
new VM();
}
By using the optimization: { minimize: false } } option in my webpack.config.js I was able to find the source of the error. In the vm2 package source code this block exists:
const HOST = {
...,
require,
...
}
which gets webpacked as:
const HOST = {
...,
__webpack_require__(952),
...
}
This clearly fails. I'm not sure what I else I can do here, is there a config somewhere I can change to
My webpack.config.js:
const path = require('path');
module.exports = {
target: 'node',
entry: './vm2index.ts',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'commonjs',
},
// optimization: {
// minimize: false,
// },
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
devtool: 'source-map',
mode: 'production',
// Add the loader for .ts files.
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader',
exclude: /node_modules/,
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader',
},
],
},
stats: {
warningsFilter: [
"Module not found: Error: Can't resolve 'encoding'",
"Cannot find SourceMap 'typescript.js.map'",
],
}
};

Related

Why isn't webpack retaining console.log statements?

I'm doing my first tests with webpack and experimenting with code splitting, and I simply wanted to log from my index.js file. It gets compiled, but it doesn't log nothing, both in development or in production mode. Files are compiled and loaded. Very strange. I'm sure I'm doing something wrong... Could you please point me in the right direction?
// index.js
import _ from 'lodash';
import Swiper from 'swiper';
import { Fancybox, Carousel, Panzoom } from "#fancyapps/ui";
function log(){
console.log('from index');
console.log(Swiper);
console.log(Fancybox, Carousel, Panzoom);
console.log(_);
}
log();
webpack config:
const path = require('path');
module.exports = {
//mode: 'development',
mode: 'production',
watch: true,
entry: {
index: './src/index.js',
//page_2: './src/page-2.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
splitChunks: {
cacheGroups: {
visuals: {
name: 'visuals',
chunks: 'all',
test: /[\\/]node_modules[\\/](swiper|#fancyapps\/ui|dom7|ssr-window)[\\/]/
},
lowdash: {
name: 'lowdash',
chunks: 'all',
test: /[\\/]node_modules[\\/]lodash[\\/]/
}
},
}
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ['#babel/preset-env'] }
}
} // babel
] // rules
} // module
};
My guess would the as part of the optimization that webpack does, it cleans out your console.logs.
You could try adding
optimization: {
minimize: false,
},
};
and see if that helps. Although I'm surprised it's doing it in dev mode as well.

How to avoid loading from chunk in webpack? [Angular] [inline js]

I am trying to bundle a angular project into a single file (js, css and html). I've managed to get the html and css working and js is also inline now (using HtmlWebpackInlineSourcePlugin). The js files generated after minification are like below:
The vendor, main and polyfill are inline in the index.html. But I see that the generated js for main and vendor js are trying to load from the chunk 3.js (this has the actual js that's written for the app).
I want this chunk also to be inline, but can't seem to find a way to do it. Even if I did manage to make it inline, how do I avoid vendor/main js from loading this chunk. The webpack config is below.
'use strict';
const webpackMerge = require('webpack-merge');
const ngw = require('#ngtools/webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const isDev = process.env.NODE_ENV !== 'production';
//just a wrapper for path
const helpers = require('./helpers');
module.exports = {
mode: 'production',
output: {
path: helpers.root('dist'),
filename: '[name].js',
},
resolveLoader: {
modules: [helpers.root('node_modules')]
},
entry: {
vendor: './src/vendor.ts',
polyfills: './src/polyfills.ts',
main: './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js', '.scss']
},
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(scss|sass)$/,
use: [
{ loader: 'style-loader', options: { sourceMap: isDev } },
{ loader: 'css-loader', options: { sourceMap: isDev } },
{ loader: 'sass-loader', options: { sourceMap: isDev } }
],
include: helpers.root('src', 'assets')
},
{
test: /\.(scss|sass)$/,
use: [
'to-string-loader',
{ loader: 'css-loader', options: { sourceMap: isDev } },
{ loader: 'sass-loader', options: { sourceMap: isDev } }
],
include: helpers.root('src', 'app')
},
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
loader: '#ngtools/webpack'
}
]
},
plugins: [
new ngw.AngularCompilerPlugin({
tsConfigPath: helpers.root('tsconfig.json'),
entryModule: helpers.root('src', 'app', 'app.module#AppModule')
}),
new HtmlWebpackPlugin({
template: 'src/index.html',
inlineSource: '.(js|css)$',
}),
new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin),
// new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/chunk/])
]
};
FYI - I want it to be a single inline file because I need to use in google apps script (editor add on).
I ended up solving this using libraryTarget in webpack to compile to umd.
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: '[name].js',
libraryTarget: "umd",
globalObject: 'this'
}

Using Imports with .Net, React.Js, and Url.Content

I am using a .Net MVC framework, and trying to render a jsx (React) file that has imports. I am including this file in the razor page (cshtml) through the standard Url.Content injection as follows:
<script src="#Url.Content("~/js/queue/QueueIndex.js")"></script>
<script>
ReactDOM.render(React.createElement(QueueIndex), document.getElementById("queue-index"));
jQuery(window).on("load scroll", function () {
'use strict'; // Start of use strict
// Loader
$("#dvLoading").fadeOut("fast");
});
</script>
If I do not have an import at the top of my React file (QueueIndex.jsx) the page loads just fine. However, I would like to import the react-table package, but if include any imports in my QueueIndex.jsx file, the page breaks.
The error I'm getting is require is not defined.
I think the solution is somewhere in the use of webpack, here is my config:
const webpack = require("webpack");
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
nhqueue: './wwwroot/js/queue/QueueIndex.jsx'
},
output: {
path: __dirname + '/wwwroot/js/',
publicPath: '/wwwroot/js/',
filename: '[name].bundle.js'
},
module: {
preLoaders: [
],
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{ test: /\.tsx?$/, loaders: ['babel', 'ts'] },
{ test: /\.json$ /, loader: "json-loader" },
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel",
query:
{
presets: ['react']
}
}
],
externals: {
"moment": "moment",
},
},
devtool: 'source-map',
target: 'web',
plugins: [
new CleanWebpackPlugin(['./wwwroot/js/*.js'], {
root: __dirname,
verbose: true,
dry: false
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin()
],
resolve: {
extensions: ['', '.jsx', '.js', '.tsx', '.ts']
},
node: {
fs: "empty",
child_process: "empty"
}
}
Unfortunately, I have had no luck there. Please let me know if you have any ideas of how to resolve this issue. Thanks!
Also, Here is the Babel configuration:
{"presets" : ["es2015", "react"]}

Webpack2: require is not defined

I get this error in app.js:
Uncaught ReferenceError: require is not defined
Why webpack require not work? Is any additional wabpack configutarion needed to make this work?
webpack.config.js
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: ['./src/app.js', './src/styles/styles.scss'],
output: {
filename: 'dist/bundle.js'
},
resolve: {
extensions: ['.js'],
},
module: {
rules: [
{ // regular css files
test: /\.css$/,
loader: ExtractTextPlugin.extract({
loader: 'css-loader?importLoaders=1',
}),
},
{ // sass / scss loader for webpack
test: /\.(sass|scss)$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
},
{
test: /\.hbs$/,
loader: 'handlebars-loader'
}
]
},
plugins: [
new ExtractTextPlugin({ // define where to save the file
filename: 'dist/[name].bundle.css',
allChunks: true,
}),
],
};
app.js
const something = require("./something.js");

Webpack file loader not recognized

I am trying to build my project using webpack and thus far I am loving it. However, now that I am trying to include font-awesome, it is annoying me quite a bit.
I have installed font-awesome through npm, and I have imported it into my project using import 'font-awesome/css/font-awesome.css'. Webpack then tries to include that file, but fails to find the appropriate loader for the font files. Here is my webpack.config.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractScss = new ExtractTextPlugin('bundle.css');
module.exports = {
entry: './app/app.tsx',
output: {
path: 'dist',
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.ts', '.js', '.tsx']
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.ts(x?)$/,
loader: 'babel?presets[]=es2015!ts'
},
{
test: /\.scss$/,
loader: extractScss.extract(['css', 'sass'])
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?limit=10000&minetype=application/font-woff'
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.ejs',
inject: false,
appMountId: 'root'
}),
new ExtractTextPlugin('bundle.css')
]
};

Categories

Resources