karma Uncaught SyntaxError: Unexpected token export - node.js

I use karma + jasmine to write test cases for vue and webpack, and it once worked. But after I upgrade vue for 1 to 2, and update vue-loader accordingly, it starts to give error.
Now when I run karma start karma.config.js, it give me error like:
Chrome 53.0.2785 (Windows 7 0.0.0) ERROR
Uncaught SyntaxError: Unexpected token export
at test/index.js:8995
My karma.config.js is:
var webpackConf = require('./webpack.config.js')
delete webpackConf.entry
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine'],
reporters: ['progress', 'html'],
htmlReporter: {
outputFile: 'tests/unit-test.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// this is the entry file for all our tests.
files: [
{pattern: './test/index.js', watched: false},
],
// we will pass the entry file to webpack for bundling.
preprocessors: {
'./test/index.js': ['webpack']
},
// use the webpack config
webpack: webpackConf,
// avoid walls of useless text
webpackMiddleware: {
noInfo: true
},
singleRun: true,
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-webpack',
'karma-htmlfile-reporter'
]
})
}
My webpack.config.js is:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: ['webpack-hot-middleware/client','./index.js'],
output: {
path: path.resolve(__dirname, '../output/static'),
publicPath: '/',
//filename: '[name].[hash].js'
filename: 'main.js'
//chunkFilename: '[id].[chunkhash].js'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
},
extensions: ['', '.js', '.vue']
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel?presets=es2015',
exclude: /node_modules/
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'index.html'),
inject: true
})
]
}
Looks like the es6 export syntax is not translated correctly. Also, I did not know where to take a look at the test/index.js:8995 because this is auto generated by webpack. The real index.js is quite simple, just 2 lines:
var testsContext = require.context('.', true, /\.spec\.js$/)
testsContext.keys().forEach(testsContext)
How to debug this and what can I do to solve the problem?

Related

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted - NodeJS, Express & Webpack

I am developing a web application using Node.js, Express & Webpack. Everything was going well until Webpack was upgraded to Webpack 5 and lots of bugs appeared. I have managed to solve all the errors but there is a warning I can't solve. I have seen this post but it's related to Angular so I don't think it helps me much: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
WARNING in ./node_modules/terser-webpack-plugin/dist/minify.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
This is my webpack.config.js; resolve fields and node-polyfill-webpack-plugin are used to solve Webpack 5 bugs and errors.
const path = require("path")
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
resolve:{
fallback: {
"fs": false,
"path": false,
"worker_threads":false,
"child_process":false,
"http": false,
"https": false,
"stream": false,
"crypto": false,
}
},
entry: {
main: './src/js/main.js',
index:'./src/js/'
},
output: {
path: path.join(__dirname, 'dist'),
//publicPath: '/',
filename: '[name].js'
},
mode:"development",
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.bpmn$/,
use: 'raw-loader'
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/index.ejs',
filename: "./index.ejs",
excludeChunks: [ 'server', 'main' ]
}),
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/bmv.ejs',
filename: "./bmv.ejs",
excludeChunks: [ 'server', 'index' ]
}),
new webpack.NoEmitOnErrorsPlugin(),
new NodePolyfillPlugin()
]
}
configure the webpack:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
'terser-webpack-plugin': path.resolve(__dirname, 'node_modules/terser-webpack-plugin/dist/minify.js'),
},
},
};

Cannot find module "fs" - at webpackMissingModule

My server starts and runs correctly, but when I hit the URL in the browser it gives an error "cannot find module 'fs'".
I tried to setting:
target: 'node', but it starts another error
node: { fs: 'empty' }, but then it gives an error "cannot find exports"
"use strict";
const webpack = require('webpack');
const argv = require('minimist')(process.argv.slice(2));
const DEBUG = !argv.release;
const path = require('path');
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
names: ['common', 'vendors'],
filename: '[name].js',
minChunks: Infinity
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
"process.argv.verbose": !!DEBUG
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
jquery: "jquery"
})
].concat(DEBUG ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: true
}
}),
new webpack.optimize.AggressiveMergingPlugin()
]);
module.exports = {
entry: {
app: path.join(__dirname, '..', 'app', 'app.js'),
vendors: [
'react',
'react-dom',
'react-bootstrap',
'react-router',
'alt',
'lodash',
'superagent',
'react-router-role-authorization',
'react-validation-decorator'
]
},
output: {
publicPath: '/js/',
path: './wwwroot/js/',
filename: '[name].js',
chunkFilename: "[id].[name].js"
},
context: path.join(__dirname, '..'),
plugins: plugins,
cache: DEBUG,
debug: DEBUG,
watch: DEBUG,
stats: {
colors: true
},
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.(less|css)$/,
loaders: ["style", "css", "less"]
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|ttf|wav|mp3|mp4)$/,
loader: 'file-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
node: {
net: 'mock',
dns: 'mock'
}
};
It should not give this error and work correctly.
I don't see any mention of the fs module in your posted webpack setup. So, my guess is that your output application (app.js?) is trying to require and use fs. Webpack is building a client-side, front-end application, one that will be loaded in the browser; fs is not available in the browser.
(Double-check and make sure you aren't trying to, for example, read and write files on the user's machine using fs inside your client-side application. That is not possible in a browser-based application. For an intro to the concept of web applications with a front end and back end, check out the article React App With Node Backend.)

How to use webpack to create a front end and a admin?

I am actually new on node.js. I am trying to create an app with admin and frontend using webpack and express. I have created an example app but now the problem is how I can create the app with the admin. Below I have shared my webpack config file
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
frontend: './src/index',
backend: './admin/index'
},
module: {
loaders: [
{
test: /\.js?$/, loader: 'babel', exclude: /node_modules/
},
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
}
]
},
resolve: {
extensions: ['', '.js']
},
output: {
path: path.join(__dirname, '/public'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './public',
hot: true
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
Webpack production configuration file
var config = require('./webpack.config.js');
var webpack = require('webpack');
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("production")
}
})
);
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
);
Is there any easy solution or what I can do now?

Webpack build fail when adding a specific external lib

It happens on a build for server side, i am already using a lot of external modules and everything worked great until now.
I am trying to add the module auth0-js and the error happens when i add the import on this lib var crypto = require('crypto'); TypeError: require is not a function.
Here is my webpack config (for server side):
const path = require('path');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
module.exports = {
entry: './handler.js',
target: 'node',
profile: false,
output: {
path: path.resolve(__dirname, '../dist-server'),
publicPath: '/',
filename: 'handler.js',
libraryTarget: 'commonjs'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, '..'),
use: 'babel-loader'
},
{
test: /\.pug$/,
use: 'pug-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
__CLIENT__: false,
__SERVER__: true
}),
new StatsPlugin('stats.json', {
chunkModules: true,
exclude: [/node_modules[\\\/]react/]
})
],
resolve: {
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
devtool: 'source-map'
};
My .babelrc file is:
{
"presets": [
"react",
"latest"
],
"plugins": [
"transform-object-rest-spread",
"transform-runtime"
]
}
I tried to remove the exclude node_modules but i get other errors.
I am curious to know how a single library can break everything, what should i do?

How to configure webpack for nodejs with server side rendering

I'm trying to setup Webpack to generate 2 bundles, one for server code with server side rendering and one for client code. So far the bundle seems to generate correctly but when I run the server code and it tries to render some of my React components it throws errors like this one:
ERROR in ./~/react-load-script/lib/index.js
Module build failed: ReferenceError: Unknown plugin "add-module-exports" specified in "/Users/alex/Development/muub/one/website/node_modules/react-load-script/.babelrc" at 0, attempted to resolve relative to "/Users/alex/Development/muub/one/website/node_modules/react-load-script"
at /Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
at Array.map (native)
at Function.normalisePlugins (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
at OptionManager.mergeOptions (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
at OptionManager.init (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
at File.initOptions (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/index.js:212:65)
at new File (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/index.js:135:24)
at Pipeline.transform (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
at transpile (/Users/alex/Development/muub/one/website/node_modules/babel-loader/lib/index.js:46:20)
at Object.module.exports (/Users/alex/Development/muub/one/website/node_modules/babel-loader/lib/index.js:163:20)
# ./App/Containers/Publish/Payment/Payment.jsx 18:0-39
# ./App/Containers/Publish/Payment/index.js
# ./App/Containers/Publish/Publish.jsx
# ./App/Containers/Publish/index.js
# ./App/Routes/index.js
# ./App/Containers/App.jsx
# ./App/index.js
# multi webpack-hot-middleware/client react-hot-loader/patch ./App
There are more errors similar to this one but related with other 3rd party npm packages.
Here is my webpack server config:
const path = require('path');
const webpack = require('webpack');
const ExternalsPlugin = require('webpack2-externals-plugin');
let conf = {
devtool: 'source-map',
context: path.resolve(__dirname),
entry: [
path.resolve(__dirname, 'index.js')
],
target: 'node',
output: {
path: path.join(__dirname, 'build'),
pathinfo: true,
filename: 'server.js',
publicPath: '/public/',
libraryTarget: 'commonjs2'
},
resolve: {
modules: ['App', 'node_modules'],
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'css-loader/locals',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
'postcss-loader'
]
},
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExternalsPlugin({
type: 'commonjs2',
include: path.join(__dirname, 'node_modules'),
exclude: [path.join(__dirname, 'node_modules', 'webpack/buildin'), path.join(__dirname, 'App')]
}),
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
}
module.exports = conf;
What could I be doing wrong?

Resources