Webpack problem generating sourcemaps -- only generated when a particular plugin is disabled - javascript

I'm using my own custom plugin to strip some optional code from a build. This works well, but for some reason it seems to be blocking generation of source maps.
My best guess is that the fact that I'm modifying the index.js output file interferes with the ability to generate a map of for that file. If I comment out the plugin, my source maps come back.
Is there perhaps something I can do to change order of plugin execution that will fix this? Or perhaps a way to strip code from source file input streams (not from the files themselves) rather than from the generated output?
I've tried explicitly adding SourceMapDevToolPlugin to my plugins, but that didn't help.
Here's my webpack.config.cjs file:
const { Compilation, sources } = require('webpack');
const { resolve } = require('path');
module.exports = env => {
const esVersion = env?.esver === '5' ? 'es5' : 'es6';
const dir = env?.esver === '5' ? 'web5' : 'web';
const chromeVersion = env?.esver === '5' ? '23' : '51';
// noinspection JSUnresolvedVariable,JSUnresolvedFunction,JSUnresolvedFunction
return {
mode: env?.dev ? 'development' : 'production',
target: [esVersion, 'web'],
entry: {
index: './dist/index.js'
},
output: {
path: resolve(__dirname, 'dist/' + dir),
filename: `index.js`,
libraryTarget: 'umd',
library: 'tbTime'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: { presets: [['#babel/preset-env', { targets: { chrome: chromeVersion } }]] }
},
resolve: { fullySpecified: false }
}
]
},
resolve: {
mainFields: ['esm2015', 'es2015', 'module', 'main', 'browser']
},
externals: { 'by-request': 'by-request' },
devtool: 'source-map',
plugins: [
new class OutputMonitor {
// noinspection JSUnusedGlobalSymbols
apply(compiler) {
compiler.hooks.thisCompilation.tap('OutputMonitor', (compilation) => {
compilation.hooks.processAssets.tap(
{ name: 'OutputMonitor', stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE },
() => {
const file = compilation.getAsset('index.js');
let contents = file.source.source();
// Strip out dynamic import() so it doesn't generate warnings.
contents = contents.replace(/return import\(.*?\/\* webpackIgnore: true \*\/.*?tseuqer-yb.*?\.join\(''\)\)/s, 'return null');
// Strip out large and large-alt timezone definitions from this build.
contents = contents.replace(/\/\* trim-file-start \*\/.*?\/\* trim-file-end \*\//sg, 'null');
compilation.updateAsset('index.js', new sources.RawSource(contents));
}
);
});
}
}()
]
};
};
Full project source can be found here: https://github.com/kshetline/tubular_time/tree/development

I think using RawSource would disable the source map. The right one for devtool is supposed to be SourceMapSource so the idea looks like following:
const file = compilation.getAsset('index.js');
const {devtool} = compiler.options;
let contents = file.source.source();
const {map} = file.source.sourceAndMap();
// your replace work
// ...
compilation.updateAsset(
'index.js',
devtool
// for devtool we have to pass map file but this the original one
// it would be wrong since you have already changed the content
? new sources.SourceMapSource(contents, 'index.js', map)
: new sources.RawSource(contents)
);

Related

Option to get a single line main.js output with only references (webpack)?

I'm new to webpack and I have been put on a project where someone was already coding something before me. I have all the source code and I have also a webpack.config.js file.
I want to rebuild the output main.js from those files but I think I might be missing some steps to get there. I use the loader babel by the way and the react library.
When I run npx webpack in the folder where the .config.js file is I have something with this structure:
/*! For license information please see main.js.LICENSE.txt */
(() => {
var e = {
418: e => {
"use strict";
var t = Object.getOwnPropertySymbols,
n = Object.prototype.hasOwnProperty,
r = Object.prototype.propertyIsEnumerable;
function o(e) {...
I want to get something that looks like this (I modified it so it is more readable but normally everything is on one line):
() => {
var __webpack_modules__ = {
"./src/components/app.js": (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
If anyone has an idea feel free to tell me, I just started using webpack two weeks ago and I might have misunderstood something.
My Webpack.config.js file
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./static/frontend"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
],
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
// This has effect on the react lib size
NODE_ENV: JSON.stringify("production"),
},
}),
new HtmlWebpackPlugin({
favicon: "./src/small-logo-orange.svg"
}),
],
};
Ok after some research I found out what was my problem.
The previous guy gave me a webpack.config.js file with no option for the mode field in :
module.exports = {
};
To get the same thing as him I need to have the mode set to 'development'
module.exports = {
mode: 'development', ...
};
See https://webpack.js.org/configuration/mode
Hope this will help someone one day.

Storybook mdx files are not displayed

I use default Storybook Webpack config alongside with data from my existed one. I don't see any *.mdx files in a stories side-bar.
At first I just have replaced all config.module.rules by rules from existed webpack config and I got this error: Unexpected default error message
Error: Unexpected default export without title: undefined
at http://localhost:6006/vendors~main.iframe.bundle.js:96519:15
at Array.forEach (<anonymous>)
at http://localhost:6006/vendors~main.iframe.bundle.js:96512:11
at ConfigApi.configure (http://localhost:6006/vendors~main.iframe.bundle.js:76149:7)
at Object.configure (http://localhost:6006/vendors~main.iframe.bundle.js:96643:17)
at configure (http://localhost:6006/vendors~main.iframe.bundle.js:95240:24)
at Object.<anonymous> (http://localhost:6006/main.iframe.bundle.js:18:36)
at Object../.storybook/generated-stories-entry.js (http://localhost:6006/main.iframe.bundle.js:19:30)
at __webpack_require__ (http://localhost:6006/runtime~main.iframe.bundle.js:854:30)
at fn (http://localhost:6006/runtime~main.iframe.bundle.js:151:20)
Then I added this loader for *.mdx files:
{
test: /\.(stories|story)\.mdx$/, use: [
require.resolve('#mdx-js/loader'),
]
}
Hence, the error disappeared but also *.mdx files are not displayed.
I tried to add "babel-loader" before "#mdx-js/loader" in this way:
{
test: /\.(stories|story)\.mdx$/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
plugins: ['#babel/plugin-transform-react-jsx'],
},
},
{
loader: '#mdx-js/loader',
options: {
compilers: [createMDXCompiler({})],
},
},
],
}
Also I checked different order for rules in config.module.rules and I added this rule directly to existed "webpack.config". I noticed that it doesn't matter what loader is in "mdx" rule, for instance, this works without errors but the files still not displayed:
{
test: /\.(stories|story)\.mdx$/,
use: ['any text]
};
mdx file sample:
import { Preview, IconGallery, IconItem } from '#storybook/addon-docs/blocks';
...
import { appConfig } from '../../config/AppConfig';
<Meta title='Theming/Icons' />
# Icons
<AppConfigContext.Provider value={appConfig}>
<IconGallery>
<IconItem name='ArrowDown'>
<Icon variant='ArrowDown' />
</IconItem>
...
</AppConfigContext.Provider>
My webpack.config.js:
'use strict';
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const ESLintPlugin = require('eslint-webpack-plugin');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
const ReactRefreshWebpackPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
const sites = require('./sites');
const postcssNormalize = require('postcss-normalize');
const appPackageJson = require(paths.appPackageJson);
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
const webpackDevClientEntry = require.resolve(
'react-dev-utils/webpackHotDevClient'
);
const reactRefreshOverlayEntry = require.resolve(
'react-dev-utils/refreshOverlayInterop'
);
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
const SITE = process.env.SITE?.toLowerCase() || sites[0];
if (!sites.includes(SITE)) {
throw new Error(
`Value of SITE: ${SITE} is not valid value. Please use one of the following [${sites.toString()}]`
);
}
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const hasJsxRuntime = (() => {
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
return false;
}
try {
require.resolve('react/jsx-runtime');
return true;
} catch (e) {
return false;
}
})();
const getRegexForIgnoreStyles = (app) => {
const test = new RegExp(
`\\.(${sites.filter((site) => site !== app).join('|')})\\.scss`
);
return { test, loader: require.resolve('ignore-loader') };
};
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// We will provide `paths.publicUrlOrPath` to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
// Get environment variables to inject into our app.
const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
const shouldUseReactRefresh = env.raw.FAST_REFRESH;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
// css is located in `static/css`, use '../../' to locate index.html folder
// in production `paths.publicUrlOrPath` can be a relative path
options: paths.publicUrlOrPath.startsWith('.')
? { publicPath: '../../' }
: {}
},
{
loader: require.resolve('css-loader'),
options: { ...cssOptions, url: false }
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize()
],
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
}
}
].filter(Boolean);
if (preProcessor) {
const options = { sourceMap: true };
if (preProcessor === 'sass-loader') {
options.additionalData = `$assets-url: '${process.env.REACT_APP_ASSETS_URL}';`;
}
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
root: paths.appSrc
}
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true
}
}
);
}
return loaders;
};
const baseConfig = {
...
}
...
const baseRules = {
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
mimetype: 'image/avif',
name: 'static/media/[name].[hash:8].[ext]'
}
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic'
}
]
],
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent: '#svgr/webpack?-svgo,+titleProp,+ref![path]'
}
}
}
]
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction
}
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true }
]
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// Babel sourcemaps are needed for debugging into node_modules
// code. Without the options below, debuggers like VSCode
// show incorrect code and set breakpoints on the wrong lines.
sourceMaps: shouldUseSourceMap,
inputSourceMap: shouldUseSourceMap
}
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
modules: {
getLocalIdent: getCSSModuleLocalIdent
}
})
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
modules: {
getLocalIdent: getCSSModuleLocalIdent
}
},
'sass-loader'
)
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx|ejs)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]'
}
}
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
]
};
const configs = sites
.map((brand) => {
return {
...baseConfig,
name: brand,
entry: isEnvProduction
? { [brand]: paths.appIndexJs }
: [paths.appIndexJs],
module: {
...baseConfig.module,
rules: [
...baseConfig.module.rules,
{
oneOf: [getRegexForIgnoreStyles(brand), ...baseRules.oneOf]
}
]
},
plugins: [...baseConfig.plugins].filter(Boolean)
};
})
.reduce((acc, item) => {
return { ...acc, [item.name]: item };
}, {});
return isEnvProduction ? [...Object.values(configs)] : configs[SITE];
};
TL;DR
obey to Storybook's default *.stories.mdx naming convention
ensure that there is no trailing ; behind your <Meta title="..." /> tag – something like this breaks the story: <Meta title="..." />;
also it seems that stories inside hidden folders (folder-name starting with a . – e.g. .stories/my.stories.ts) will be ignored as well. Remove the . from the folder name in those cases
when you add some html-tags (e.g. <br/>) after a <Story> or <Canvas> (or any other storybook-mdx-component, make sure to add a line-break between the <Story> and your <br/>. Otherwise this will also cause an error, making the file disappear.
Detail
In my case the problem was that I didn't want to go with Storybook's default naming convention *.stories.mdx. I tried to omit the .stories part (i.e. having files like button.mdx instead of button.stories.mdx) and reconfigured the main.js accordingly. But this seems to not work – no mdx-files were showing up. Once I reverted back to .stories.mdx the mdx files were displayed again in the storybook side-bar.
Update
Another problem I noticed is very subtle and easy to miss. If you or your code formatter by any chance added a ; after your <Meta title="..."> tag, your file will not be shown in the sidebar. So keep an eye on that:
<!-- note the trailing ";" -->
<Meta title="My/Title" />;
<!-- after removing it, your file will show again -->
<Meta title="My/Title" />

How use sql.js-httpvfs library in Gatsby?

I try to use sql.js-httpvfs library inside my project. However, I am not successed yet. I am not expert about node.js.
What I do?
Firstly, need to webpack.config to Gatsby for that I create gatsby-node.js file and add the below code inside it.
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
entry: "./src/index.js",
module: {
rules: [
{
test: "/.tsx?$/",
use: "ts-loader",
exclude: "/node_modules/",
},
],
},
output: {
filename: "bundle.js",
},
devServer: {
publicPath: "/dist",
},
});
};
Inside my index.js page, I add the code;
import { createDbWorker } from "sql.js-httpvfs";
const workerUrl = new URL(
"sql.js-httpvfs/dist/sqlite.worker.js",
import.meta.url
);
const wasmUrl = new URL("sql.js-httpvfs/dist/sql-wasm.wasm", import.meta.url);
function load() {
const worker = createDbWorker(
[
{
from: "inline",
config: {
serverMode: "full",
url: "../myTestDb.sqlite3",
requestChunkSize: 4096,
},
},
],
workerUrl.toString(),
wasmUrl.toString()
);
const result = worker.db.query(`select * from districts`);
document.body.textContent = JSON.stringify(result);
}
load();
But I got error.
There is no any created bundle.js or folder like dist.

Override what's bundled in webpack based on file extension

I'm trying to figure out whether or not webpack can do something like this. I have some code that I want to be bundled for a specific device. So I created a ViewFactories.ios.tsx and I also have ViewFactories.tsx. The problem i'm encountering is that the if I ignore the .ios.tsx in the loader test, it still gets bundled. I'm using the ignore-bundler plugin to ignore the .ios.tsx files, but the reference is just empty. ie:
/** still getting loaded here: **/
const ViewFactories_ios_1 = __importDefault(__webpack_require__(/*! ./ViewFactories.ios */ "./build/app/src/modules/layouts/factories/ViewFactories.ios.tsx"));
/*** the referenced section, but blank now ***/
/***/ "./build/app/src/modules/layouts/factories/ViewFactories.ios.tsx":
/*!***********************************************************************!*\
!*** ./build/app/src/modules/layouts/factories/ViewFactories.ios.tsx ***!
\***********************************************************************/
/*! dynamic exports provided */
/*! all exports used */
/***/ (function(module, exports) {
/***/ }),
What I really want is the reference to ViewFactories.tsx instead of ViewFactories.ios.tsx.
Is there some sort of dependency graph in webpack that I can access to tell the loader to use the default instead of the .ios.tsx?
My webpack config:
{
test: (modulePath) => {
if (/\.ios\./.test(modulePath)) {
console.log(modulePath);
return false;
}
return /\.tsx?$/.test(modulePath);
},
loader: "awesome-typescript-loader",
options: {
configFileName: 'tsconfig.web.json',
transpileOnly: true,
errorsAsWarnings: true,
}
},
{
test: (modulePath) => {
if (/\.ios\./.test(modulePath)) {
console.log('Ignored: ', modulePath);
return true;
}
return false;
},
loader: 'ignore-loader'
},
Just build two bundles, with shared config options for whatever is the same?
// webpack.config.js for two different bundles
let sharedModuleDef = {
rules: ...
}
let sharedPlugins = ...
let iosBundle = {
entry: "src/ios.entry.js",
output: {
path: ...
filename: "ios.bundle.js"
},
module: sharedModuleDef,
...
};
let everythingElse = {
entry: "src/main.entry.js",
output: {
path: ...
filename: "standard.bundle.js"
},
module: sharedModuleDef,
...
};
module.exports = [iosBundle, everythingElse];

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

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

Categories

Resources