ERROR from UglifyJs: SyntaxError: Unexpected token: operator (>) - javascript

I'm getting an error when trying to run my webpack for production.
ERROR in js/main.21dbce548a76ffc14cfb.js from UglifyJs
SyntaxError: Unexpected token: operator (>) [./~/tmi.js/lib/utils.js:3,0][js/main.21dbce548a76ffc14cfb.js:3529,20]
utils.js:3,0 (which is the same as in my minified js) is:
// Return the second value if the first value is undefined..
get: (obj1, obj2) => { return typeof obj1 === "undefined" ? obj2 : obj1; },
So I assume from that the error is thrown because it's reading ES6 but it doesn't understand ES6? (The arrow function)
I don't see what's going wrong here, this is my webpack.config.js
// changed some loader syntax after reading
// https://webpack.js.org/how-to/upgrade-from-webpack-1/
const path = require(`path`);
const webpack = require(`webpack`);
const {UglifyJsPlugin} = webpack.optimize;
const CopyWebpackPlugin = require(`copy-webpack-plugin`);
const ExtractTextWebpackPlugin = require(`extract-text-webpack-plugin`);
const configHtmls = require(`webpack-config-htmls`)();
const extractCSS = new ExtractTextWebpackPlugin(`css/style.css`);
// change for production build on different server path
const publicPath = `/`;
// hard copy assets folder for:
// - srcset images (not loaded through html-loader )
// - json files (through fetch)
// - fonts via WebFontLoader
const copy = new CopyWebpackPlugin([{
from: `./src/assets`,
to: `assets`
}], {
ignore: [ `.DS_Store` ]
});
const config = {
entry: [
`./src/css/style.css`,
`./src/js/script.js`
],
resolve: {
// import files without extension import ... from './Test'
extensions: [`.js`, `.jsx`, `.css`]
},
output: {
path: path.join(__dirname, `server`, `public`),
filename: `js/[name].[hash].js`,
publicPath
},
devtool: `sourcemap`,
module: {
rules: [
{
test: /\.css$/,
loader: extractCSS.extract([
{
loader: `css`,
options: {
importLoaders: 1
}
},
{
loader: `postcss`
}
])
},
{
test: /\.html$/,
loader: `html`,
options: {
attrs: [
`audio:src`,
`img:src`,
`video:src`,
`source:srcset`
] // read src from video, img & audio tag
}
},
{
test: /\.(jsx?)$/,
exclude: /node_modules/,
use: [
{
loader: `babel`
},
{
loader: `eslint`,
options: {
fix: true
}
}
]
},
{
test: /\.(svg|png|jpe?g|gif|webp)$/,
loader: `url`,
options: {
limit: 1000, // inline if < 1 kb
context: `./src`,
name: `[path][name].[ext]`
}
},
{
test: /\.(mp3|mp4)$/,
loader: `file`,
options: {
context: `./src`,
name: `[path][name].[ext]`
}
}
]
},
plugins: [
extractCSS,
copy
]
};
if(process.env.NODE_ENV === `production`){
//image optimizing
config.module.rules.push({
test: /\.(svg|png|jpe?g|gif)$/,
loader: `image-webpack`,
enforce: `pre`
});
config.plugins = [
...config.plugins,
new UglifyJsPlugin({
sourceMap: true, // false returns errors.. -p + plugin conflict
comments: false
})
];
}
config.plugins = [...config.plugins, ...configHtmls.plugins];
module.exports = config;

OP's error is from UglifyJs, as is solved in the accepted answer, some people to this page may get the error from babel, in which case, fix it with: add "presets": ["es2015"] either to the options.presets section of babel-loader, or to .babelrc.

UglifyJs2 has a Harmony branch which accepts ES6 syntax to be minified. At this moment, you need to create a fork of webpack and point webpack to that fork.
I recently answered a couple of similar questions. Please have a look at #38387544 or #39064441 for detailed instructions.

In my case I was using webpack version 1.14
I got help from git ref
steps:
install yarn add uglifyes-webpack-plugin (and removed yarn remove uglifyjs-webpack-plugin)
then install yarn add uglify-js-es6
In webpack.config.js file change new webpack.optimize.UglifyJsPlugin to
new UglifyJsPlugin
then I was able to build. Thanks

Related

cannot babel transform .marko files with webpack 4

i have a working marko setup for my widget. Im using webpack 4 and babel 7. When i add babel-loader to .marko files, the webpack compiler throws because it couldn't recognize marko's syntax as valid javascript. However the loader should work after the marko transpilation.
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Volumes/Workspace/product-curator-widget/src/index.marko: A class name is required (1:6)
> 1 | class {
| ^
2 | onCreate () {
index.marko
class {
onCreate () {
this.state = {
items: [ {label: 'foo'}, {label: 'bar'} ]
}
const pr = new Promise((resolve) => resolve()) //trying to transpile this arrow function
}
}
<paper>
<chip for (item in state.items) label="${item.label}" value="${item.value}" />
</paper>
webpack.config.js
'use strict'
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports = () => ({
mode: 'development',
devtool: 'cheap-source-map',
entry: [
'core-js',
'./src/index.js'
],
resolve: {
extensions: ['.js', '.marko'],
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/, /\.test\.js$/],
use: ['babel-loader'],
},
{
test: /\.marko$/,
exclude: [/node_modules/, /\.test\.js$/],
use: ['#marko/webpack/loader', 'babel-loader'],
},
{
test: /\.scss$/,
exclude: [/node_modules/],
use: ['style-loader', 'css-loader', 'sass-loader'],
}
],
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: './src/index.html'
}),
new CleanWebpackPlugin()
],
})
babel.config.js
module.exports = function (api) {
api.cache(true)
return {
"plugins": [
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-regenerator",
],
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "10"
}
}
]
]
}
}
Loaders in webpack are evaluated from right to left. In this case, you'll want #marko/webpack/loader to be the first loader to run (put it last in the array), so by the time babel-loader is called, the .marko file has been compiled to JS.
Side note: if you're using Marko components that have been published to npm, you don't want to ignore node_modules. Marko recommends publishing the source .marko files because the compiler produces different output for the server vs the browser. Additionally, the compilation output can be different depending on the version of Marko your app is using.
{
test: /\.marko$/,
use: ['babel-loader', '#marko/webpack/loader'],
},

MQTT.js and Webpack - "WS is not a constructor"

I am trying to bundle one of our microservices which is using MQTT.js and I am struggling with really strange issue.
It is working fine without bundling, so ws is available in node_modules.
Stuff which I think matters:
error:
TypeError: WS is not a constructor
at WebSocketStream (dist/index.js:159329:16)
at createWebSocket (dist/index.js:147450:10)
at Object.buildBuilderBrowser (dist/index.js:147476:10)
at MqttClient.wrapper [as streamBuilder] (dist/index.js:147937:36)
at MqttClient._setupStream (dist/index.js:146471:22)
at new MqttClient (dist/index.js:146452:8)
at Function.connect (dist/index.js:147940:10)
webpack config:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const { NODE_ENV = 'production' } = process.env;
module.exports = {
entry: { index: './src/index.ts' },
mode: NODE_ENV,
target: 'node',
watch: NODE_ENV === 'development',
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
resolve: {
extensions: ['.ts', '.js'],
},
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.ts$/,
use: [{ loader: 'ts-loader', options: { transpileOnly: true } }],
},
{
test: /(\.md|\.map)$/,
loader: 'null-loader',
},
],
},
};
Function where it happens:
createMqttClient(): MqttClient {
return mqtt.connect(this.mqttOptions.url, { ...this.mqttOptions.options });
}
The url is like: ssl://url-to-our-mqtt
Can anybody help please?
I also ran into same issue.
The problem for me was that I used
plugins: [
new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
],
in webpack.config.js order to fix the shebang error that comes with mqtt.js since it is a CLI tool.
Then instead I have used
{
test: [
/node_modules[/\\]mqtt[/\\]mqtt.js/,
/node_modules[/\\]mqtt[/\\]bin[/\\]sub.js/,
/node_modules[/\\]mqtt[/\\]bin[/\\]pub.js/,
],
loader: 'shebang-loader'
},
And my problem was fixed. Do you also use mqtt/dist/mqtt.js instead of mqtt in your imports or if you do something similar to mine, the shebang-loader rule I have posted above might solve your problem.
I experienced the same with Amazon aws-iot-device-sdk-js and Microsoft azure-iot-device-mqtt which both include mqtt.
The initial issue is the build error:
ERROR in ./node_modules/mqtt/mqtt.js Module parse failed: Unexpected character '#' (1:0)
This error is caused by the package mqtt. Three files (mqtt.js, pub.js and sub.js) contain a shebang line
#!/usr/bin/env node
The solution using module replacement suggested some places
plugins: [
new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
],
unfortunately changes the build error with the run time error
TypeError: WS is not a constructor
As mentioned in other answers, webpack can be configured (https://webpack.js.org/concepts/loaders/) to use the shebang loader (https://www.npmjs.com/package/shebang-loader)
TL;DR
Install shebang-loader
npm install shebang-loader --save
In webpack.config.js use the loader
module.exports = {
...
module: {
rules: [
{
test:
[
/.*mqtt\.js$/,
/.*sub\.js$/,
/.*pub\.js$/
],
use: 'shebang-loader'
}
]
}
}

How do I fingerprint images and other static assets in Ionic for cache busting?

I have extended default web pack config in Ionic v3 for forcing cache busting.
I am able to fingerprint generated JavaScript artifacts, but I am unable to fingerprint images and JSON files under the assets folder. I took Help from Bundled files and cache-busting.
An excerpt of webpack config.js
module.exports = {
// ...
output: {
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js',
},
plugins: [
new WebpackChunkHash({algorithm: 'md5'}) // 'md5' is default value
]
}
The above is the approach for fingerprinting JavaScript bundles, and it's working fine. I want to add hashes/fingerprint images and JSON files inside the assets folder. I used the same approach for images also, but it did not work.
I have extended webpack config.js and added a new rule for images. By default webpack directly copies the images and assets to the output folder.
Copy Config.js
module.exports = {
copyAssets: {
src: ['{{SRC}}/assets/**/*'],
dest: '{{WWW}}/assets'
},
copyIndexContent: {
src: ['{{SRC}}/index.html', '{{SRC}}/manifest.json', '{{SRC}}/service-worker.js'],
dest: '{{WWW}}'
},
copyFonts: {
src: ['{{ROOT}}/node_modules/ionicons/dist/fonts/**/*', '{{ROOT}}/node_modules/ionic-angular/fonts/**/*'],
dest: '{{WWW}}/assets/fonts'
},
Here images and other assets are directly copied.
I have added a new rule in extended webpack.config.js, but the build process is ignoring it. How do I fix this issue?
Excerpt of webpack config.js
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name:'[name].[hash].[ext]',//adding hash for cache busting
outputPath:'assets/imgs',
publicPath:'assets/imgs'
},
entire Webpack.config.js
/*
* The webpack config exports an object that has a valid webpack configuration
* For each environment name. By default, there are two Ionic environments:
* "dev" and "prod". As such, the webpack.config.js exports a dictionary object
* with "keys" for "dev" and "prod", where the value is a valid webpack configuration
* For details on configuring webpack, see their documentation here
* https://webpack.js.org/configuration/
*/
var path = require('path');
var webpack = require('webpack');
var ionicWebpackFactory = require(process.env.IONIC_WEBPACK_FACTORY);
var ModuleConcatPlugin = require('webpack/lib/optimize/ModuleConcatenationPlugin');
var PurifyPlugin = require('#angular-devkit/build-optimizer').PurifyPlugin;
var optimizedProdLoaders = [
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.js$/,
loader: [
{
loader: process.env.IONIC_CACHE_LOADER
},
{
loader: '#angular-devkit/build-optimizer/webpack-loader',
options: {
sourceMap: true
}
},
]
},
{
test: /\.ts$/,
loader: [
{
loader: process.env.IONIC_CACHE_LOADER
},
{
loader: '#angular-devkit/build-optimizer/webpack-loader',
options: {
sourceMap: true
}
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name:'[name].[hash].[ext]',
outputPath:'assets/imgs',
publicPath:'assets/imgs'
},
},
{
loader: process.env.IONIC_WEBPACK_LOADER
}
]
}
];
function getProdLoaders() {
if (process.env.IONIC_OPTIMIZE_JS === 'true') {
return optimizedProdLoaders;
}
return devConfig.module.loaders;
}
var devConfig = {
entry: process.env.IONIC_APP_ENTRY_POINT,
output: {
path: '{{BUILD}}',
publicPath: 'build/',
filename: '[name].js',
devtoolModuleFilenameTemplate: ionicWebpackFactory.getSourceMapperFunction(),
},
devtool: process.env.IONIC_SOURCE_MAP_TYPE,
resolve: {
extensions: ['.ts', '.js', '.json'],
modules: [path.resolve('node_modules')]
},
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.ts$/,
loader: process.env.IONIC_WEBPACK_LOADER
},
{
test: /\.(jpg|png)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath:'assets/imgs',
publicPath:'assets/imgs'
},
}},
]
},
plugins: [
ionicWebpackFactory.getIonicEnvironmentPlugin(),
ionicWebpackFactory.getCommonChunksPlugin()
],
// Some libraries import Node.js modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
var prodConfig = {
entry: process.env.IONIC_APP_ENTRY_POINT,
output: {
path: '{{BUILD}}',
publicPath: 'build/',
filename: '[name].js',
devtoolModuleFilenameTemplate: ionicWebpackFactory.getSourceMapperFunction(),
},
devtool: process.env.IONIC_SOURCE_MAP_TYPE,
resolve: {
extensions: ['.ts', '.js', '.json'],
modules: [path.resolve('node_modules')]
},
module: {
loaders: getProdLoaders()
},
plugins: [
ionicWebpackFactory.getIonicEnvironmentPlugin(),
ionicWebpackFactory.getCommonChunksPlugin(),
new ModuleConcatPlugin(),
new PurifyPlugin()
],
// Some libraries import Node.js modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
module.exports = {
dev: devConfig,
prod: prodConfig
}
Using Webpack 4 you should not need any additional plugins or loaders.
It will give you the naming option [contenthash].
Also, it looks like you have this block nested under the test: .ts block.
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name:'[name].[hash].[ext]', // Adding hash for cache busting
outputPath:'assets/imgs',
publicPath:'assets/imgs'
}
}
Ultimately, you can do something like this:
// Copy static assets over with file-loader
{
test: /\.(ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: '[name].[contenthash].[ext]'},
},
{
test: /\.(woff|woff2|eot|ttf|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: 'fonts/[name].[contenthash].[ext]'},
},
{
test: /\.(jpg|gif|png|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: 'images/[name].[contenthash].[ext]'},
}
]
Using [chunkhash] instead of content should still work, and if you're not using webpack4 do that, but otherwise for more information see this issue for an explanation.
For more help, read the long-term caching performance guide from Google and the latest caching documentation from Webpack.
the files copied via CopyPlugin will not pass to loaders.
So even you have correct loader setting with hashname for images, it doesn't work.
but you can see https://github.com/webpack-contrib/copy-webpack-plugin#template
the CopyPlugin provide you a way to specify output name which can be set with hash:
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/',
to: 'dest/[name].[hash].[ext]',
toType: 'template',
},
]),
],
};
Eventually, I used gulp for fingerprinting static assets.
Drop Angular Output hashing and build the application.ng build --prod --aot --output-hashing none .
post-build execute a gulp script which would fingerprint all the assets and update the references.
npm i gulp gulp-rev gulp-rev-delete-original gulp-rev-collector
gulpfile.js
const gulp = require('gulp');
const rev = require('gulp-rev');
const revdel = require('gulp-rev-delete-original');
const collect = require('gulp-rev-collector');
// finger priniting static assets
gulp.task('revision:fingerprint', () => {
return gulp
.src([
'dist/welcome/**/*.css',
'dist/welcome/**/*.js',
'dist/welcome/**/*.{jpg,png,jpeg,gif,svg,json,xml,ico,eot,ttf,woff,woff2}'
])
.pipe(rev())
.pipe(revdel())
.pipe(gulp.dest('dist/welcome'))
.pipe(rev.manifest({ path: 'manifest-hash.json' }))
.pipe(gulp.dest('dist'));
});
gulp.task('revision:update-fingerprinted-references', () => {
return gulp
.src(['dist/manifest-hash.json', 'dist/**/*.{html,json,css,js}'])
.pipe(collect())
.pipe(gulp.dest('dist'));
});
gulp.task(
'revision',
gulp.series(
'revision:fingerprint',
'revision:update-fingerprinted-references'));
Add a new script in package.json
"gulp-revision": "gulp revision"
Execute npm run gulp-revision Post-build.
Solving Browser Cache Hell With Gulp-Rev
Using webpack-assets-manifest you can generate a map of asset names to fingerprinted names like so:
{
"images/logo.svg": "images/logo-b111da4f34cefce092b965ebc1078ee3.svg"
}
Using this manifest you can then rename the assets in destination folder, and use the "correct", hash-inclusive src or href in your project.
The fix isn't framework-specific.

Unexpected token m in JSON at position 0 error

On compiling an app and trying to implement the i18n library with webpack, I face this error:
ERROR in ./node_modules/bundle-loader?lazy&name=lang-pt!./src/locales/pt/translation.json
Module parse failed: Unexpected token m in JSON at position 0
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token m in JSON at position 0
at JSON.parse (<anonymous>)
at JsonParser.parse (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\JsonParser.js:15:21)
at doBuild.err (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\NormalModule.js:367:32)
at runLoaders (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\NormalModule.js:264:12)
at C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:370:3
at iterateNormalLoaders (C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:211:10)
at C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:183:6
at runSyncOrAsync (C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:130:11)
at C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:175:3
at loadLoader (C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\loadLoader.js:36:3)
at iteratePitchingLoaders (C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:169:2)
at runLoaders (C:\Users\vasco.bento\ContactosWebPack\node_modules\loader-runner\lib\LoaderRunner.js:362:2)
at NormalModule.doBuild (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\NormalModule.js:219:3)
at NormalModule.build (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\NormalModule.js:337:15)
at Compilation.buildModule (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\Compilation.js:346:10)
at factory.create (C:\Users\vasco.bento\ContactosWebPack\node_modules\webpack\lib\Compilation.js:572:15)
# ./node_modules/aurelia-i18n/dist/native-modules/aurelia-i18n.js
# ./src/main.js
# ./node_modules/aurelia-webpack-plugin/runtime/empty-entry.js
# multi aurelia-webpack-plugin/runtime/empty-entry aurelia-webpack-plugin/runtime/pal-loader-entry aurelia-bootstrapper
ERROR in chunk app [entry]
[name].[hash].bundle.js
Cannot read property 'replace' of undefined
This repeats for the other language I have in the locales folder, which is correctly placed in the src folder, even if the JSON files are completely empty, the same error occurs.
Here's the webconfig.js file:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
const {
AureliaPlugin,
ModuleDependenciesPlugin
} = require('aurelia-webpack-plugin');
const {
ProvidePlugin
} = require('webpack');
const {
BundleAnalyzerPlugin
} = require('webpack-bundle-analyzer');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig);
// primary config:
const title = 'Aurelia Navigation Skeleton';
const outDir = path.resolve(__dirname, project.platform.output);
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
const cssRules = [{
loader: 'css-loader'
}];
module.exports = ({
production,
server,
extractCss,
coverage,
analyze
} = {}) => ({
resolve: {
extensions: ['.js'],
modules: [srcDir, 'node_modules']
},
entry: {
app: ['aurelia-bootstrapper'],
vendor: ['bluebird']
},
mode: production ? 'production' : 'development',
output: {
path: outDir,
publicPath: baseUrl,
filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
},
performance: {
hints: false
},
devServer: {
contentBase: outDir,
// serve index.html for all 404 (required for push-state)
historyApiFallback: true
},
devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map',
module: {
rules: [
// CSS required in JS/TS files should use the style-loader that auto-injects it into the website
// only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
{
test: /\.css$/i,
issuer: [{
not: [{
test: /\.html$/i
}]
}],
use: extractCss ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: cssRules
}) : ['style-loader', ...cssRules]
},
{
test: /\.css$/i,
issuer: [{
test: /\.html$/i
}],
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
use: cssRules
},
{
test: /\.html$/i,
loader: 'html-loader'
},
{
test: /\.js$/i,
loader: 'babel-loader',
exclude: nodeModulesDir,
options: coverage ? {
sourceMap: 'inline',
plugins: ['istanbul']
} : {}
},
{
test: /\.json$/i,
loader: 'json-loader'
},
// use Bluebird as the global Promise implementation:
{
test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/,
loader: 'expose-loader?Promise'
},
// embed small images and fonts as Data Urls and larger ones as files:
{
test: /\.(png|gif|jpg|cur)$/i,
loader: 'url-loader',
options: {
limit: 8192
}
},
{
test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff2'
}
},
{
test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
// load these fonts normally, as files:
{
test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i,
loader: 'file-loader'
}
]
},
plugins: [
new AureliaPlugin(),
new ProvidePlugin({
'Promise': 'bluebird'
}),
new ModuleDependenciesPlugin({
'aurelia-testing': ['./compile-spy', './view-spy'],
'aurelia-i18n': [{
name: 'locales/en/translation.json',
chunk: 'lang-en'
}, {
name: 'locales/pt/translation.json',
chunk: 'lang-pt'
}]
}),
new HtmlWebpackPlugin({
template: 'index.ejs',
minify: production ? {
removeComments: true,
collapseWhitespace: true
} : undefined,
metadata: {
// available in index.ejs //
title,
server,
baseUrl
}
}),
...when(extractCss, new ExtractTextPlugin({
filename: production ? '[contenthash].css' : '[id].css',
allChunks: true
})),
...when(production, new CopyWebpackPlugin([{
from: 'static/favicon.ico',
to: 'favicon.ico'
}])),
...when(analyze, new BundleAnalyzerPlugin())
]
});
The issue in the above code happens at
{
test: /\.json$/i,
loader: 'json-loader'
},
Which if you comment, lets the app compile without issues, I've searched but event though I've found similar problems to this one, I haven't found a working solution, if anyone has any suggestion in how I can solve this problem I would appreciate it.
Thanks in advance.
The reason it says unexpected token m is because the json-loader transforms your json into a javascript file which starts with module.exports = ...
Of course that is not valid json (json must always start with opening brace {), hence it nags about the "m" of "module".
In other words, this error is indicative of webpack trying to apply json-loader twice in a row. Changing json-loader to raw-loader should get rid of webpack's wrapper javascript and pass the json as-is to whatever other plugin might be trying to load it as raw json.
Here's a related issue that might help you get this cleared up:
https://github.com/webpack-contrib/json-loader/issues/13
I didn't have the loader set in my script and i fixed it by adding this to my headers. In my case this was just a API call to my Smart lighting system
const body =
{
"device": "2B:5A:D4:AD",
"model": "H619E",
"cmd": {
"name": "turn",
"value": "off"
}
}
let res = await fetch('https://developer-api.govee.com/v1/devices/control', {
method: 'put',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
You can remove this error from the backend side by just send response in valid JSON format. So automatically error will go from the frontend side.
Just add a line in the backend where send response.
return res.status(201).json({
message: 'Success',
})

Webpack web-workers loader not working

I'm building an app using webpack and I'm trying to add some web workers, I'm using a built-in plugin to load them, but I followed the example here, the official repository, and I couldn't make it work.
My webpack.dev.js looks like this:
import webpack from 'webpack';
import assign from 'object-assign';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import prodCfg from './webpack.prod.config.js';
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var DEBUG = process.env.NODE_ENV !== 'production' ? true : false;
var styles = 'css!less';
Object.assign = assign;
export default function (app) {
const config = Object.assign(prodCfg, {
devtool: 'cheap-module-inline-source-map',
entry:
[
'webpack-hot-middleware/client',
'./client',
'styles/main.less'
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
plugins: [
[
'react-transform', {
transforms: [{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module']
}]
}
]
]
}
},
{
test: /\.css$/,
loader: DEBUG ? 'style!' + styles : ExtractTextPlugin.extract(styles)
},
{
test: /\.less$/,
loader: DEBUG ? 'style!' + styles : ExtractTextPlugin.extract(styles)
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin("style.css", {allChunks: true })
],
worker: {
output: {
filename: "hash.worker.js",
chunkFilename: "[id].hash.worker.js"
}
}
});
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));
}
and when I try to load the file I try it like this:
var Worker = require("worker!worker.js");
It would never find the file, the only files exported by webpack are bundle.js and style.css, it looks like the worker loader is not loading anything at all, or maybe I just don't understand the logic behind the loader, anyway there isn't much documentation about this nor implemented examples. So I hope someone had implemented this successfully and can shed some light on my problem.
Any help would be very welcomed! Thank you very much in advance!
You need to put it in the loaders section -
in your webpack config, something like
const config = Object.assign(prodCfg, {
...
module: {
loaders: [
...
{
test: /\.less$/,
loader: DEBUG ? 'style!' + styles : ExtractTextPlugin.extract(styles)
},
{
test: /worker\.js$/,
loader: 'worker'
}
...
then you should see it as a separate output of webpack.
Hope it helps
In the example you linked to, your line here:
var Worker = require("worker!worker.js");
Looks like this:
var Worker = require("worker!./worker");
Note that there is a ./ to indicate a relative path. Also, you do not need the .js when calling require on another file.
Do you have a file called worker.js relative to your shared code?

Categories

Resources