How to load library source maps using webpack? - javascript

I'm building two projects with webpack; one is a library for the other.
Is it possible to consume the sourcemaps from my library project when building my wrapper project? I would like the ability to debug my library code from my wrapper UI.
My build works correctly in that the library is built in. The only issue is sourcemaps. The JavaScript I see in the browser debugger is uglified, because sourcemaps are unavailable.
Snippet of my project structure:
+-- my-ui/
+-- dist/
+-- my-ui.js
+-- my-ui.js.map
+-- node_modules/
+-- my-lib/
+-- dist/
+-- bundle.js
+-- bundle.js.map
Snippet from webpack.config.js:
module.exports = {
entry: './src/js/main.jsx',
output: {
path: path.join(__dirname, 'dist'),
filename: 'my-ui.js',
library: 'my-ui',
libraryTarget: 'umd'
},
devtool: 'source-map',
module: {
loaders: [
{test: /\.jsx?$/, loader: 'babel', include: path.join(__dirname, 'src')}
]
},
plugins: [
new Clean('dist'),
new HtmlWebpackPlugin({
template: 'src/index.html',
inject: true
})
]
};

I finally figured out my issue...
Thanks to #BinaryMuse for the tip on source-map-loader. This indeed was the right way to go, though it wasn't working for me initially.
What I eventually realized is that I need to enable the source-map-loader for webpack in both "my-lib" and "my-ui". Without source-map-loader in "my-lib" webpack config, the source-map-loader inside "my-ui" errors (with a warning message sadly) because it cannot locate source maps for transitive dependencies of "my-lib". Apparently the source maps are so good that source-map-loader is able to peek at all aspects of the dependency tree.
Also of note, I ran into an issue using source-map-loader in conjunction with react-hot-loader. See, react-hot-loader does not include source maps. When source-map-loader tries to find them (because it's just scanning everything), it cannot and aborts everything.
Ultimately, I'd like source-map-loader to be more fault tolerant, but when set up correctly, it does work!
devtool: 'source-map',
module: {
preLoaders: [
{test: /\.jsx?$/, loader: 'eslint', exclude: /node_modules/},
{test: /\.jsx?$/, loader: 'source-map', exclude: /react-hot-loader/}
],
loaders: [
{test: /\.jsx?$/, loader: 'raect-hot!babel', exclude: /node_modules/}
]
}

My answer is similar to #Jeff Fairley's and I had the same directory structure, with the only difference being that I was using module: { rules: [] } instead of his module: { preLoaders: [..], loaders: [...]}. This is what I had to add to my webpack.config.js file:
mode: 'development',
devtool: 'eval-source-map',
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
}
]
},
Then I ran
npm i -D source-map-loader
and I saw the TypeScript source code of the dependency I was using when clicking through tracebacks in Chrome's devtools. See the Webpack docs for source-map-loader.

I am using create-react-app and this is how I Fixed it (without running eject cmd)
Note : If your app is already overriding webpack config using react-app-rewired you can ignore first three steps.
npm i react-app-rewired -D - This will help you to override webpack
configuration.
package.json - change your scripts, replace react-scripts with react-app-rewired
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
}
config-overrides.js - create this file in the parent level of the app.
npm i source-map-loader -D - To load source maps (assuming that your lib's dist has source map file). It doesn't matter which build tool(ex: Rollup, webpack or parcel) you use to generate sourcemap.
Copy below code in config-overrides.js
module.exports = {
webpack: (config, env) => {
// Load source maps in dev mode
if (env === 'development') {
config.module.rules.push({
test: /\.(js|mjs|jsx|ts|tsx)$/,
use: ['source-map-loader'],
enforce: 'pre',
});
// For `babel-loader` make sure that sourceMap is true.
config.module.rules = config.module.rules.map(rule => {
// `create-react-app` uses `babel-loader` in oneOf
if (rule.oneOf) {
rule.oneOf.map(oneOfRule => {
if (
oneOfRule.loader &&
oneOfRule.loader.indexOf('babel-loader') !== -1
) {
if (oneOfRule.hasOwnProperty('options')) {
if (oneOfRule.options.hasOwnProperty('sourceMaps')) {
// eslint-disable-next-line no-param-reassign
oneOfRule.options.sourceMaps = true;
}
}
}
});
}
return rule;
});
}
return config;
},
};
Restart your app (if it's already running). source files get loaded in different locations, based on path in map file. Check all folders patiently :)
Note :
1. Your source maps get loaded in one of the folder(ex : localhost:3000 or webpack:/// ) based on path it reads from xxx.js.map file.
2. If you are using rollup for your libs, please make sure you give proper path in the configuration file (output.sourcemapPathTransform ), This will help to load sourcemaps in the proper location.

You should be able to use any of the eval source map options that Webpack provides.
Really that just amounts to setting the right devtool option in your webpack.config.js for the my-lib project.
devtool: 'eval',
eval and eval-source-map should both work.
See the Webpack documentation for the various options.

Related

How to transpile and minify single file with webpack?

I have a React application, and in my application I'm relying on react-scripts, so the build command is defined like this "build": "react-scripts build", and it works all fine. Now, the point is that inside my src directory I have a JS file called wrapper.js, which is a standalone file, and it is pure JS, no React stuff, but it uses ES6 and some newer features. So, what I want to do is that, I want create a new command, which will transpile and minify this file and will create a standalone copy of it. I thought to use webpack and I created a webpack.config.js file in the root of my project, which looks like this:
const path = require('path');
const MinifyPlugin = require('babel-minify-webpack-plugin');
module.exports = {
mode: 'production',
output: {
path: __dirname + 'build',
publicPath: '/build/',
filename: 'wrapper.js',
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src', 'wrapper.js')
],
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
},
plugins: [
new MinifyPlugin()
]
};
And I added the following to my package.json file "wrapper": "webpack". Now, when I run npm run-scripts wrapper, it executes the webpack command, but it throws error. The output looks like this:
> webpack
Hash: 0aa67383ec371b8b7cd1
Version: webpack 4.19.1
Time: 362ms
Built at: 04/06/2019 10:54:46 AM
1 asset
Entrypoint main = wrapper.js
[0] ./src/index.js 223 bytes {0} [built] [failed] [1 error]
ERROR in ./src/index.js 22:4
Module parse failed: Unexpected token (22:4)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
> <Root />,
| document.getElementById('root'),
| );
What I see is that the problem is that webpack also tries to transpile and minify other files in my src directory, because it seems it has hit my React app's index.js file. How can I exclude everything? Or more precisely, how can I tell webpack to transpile and minify only the file /src/wrapper.js, and not to touch anything else at all?
Lighter weight alternative could be to create a script in your package.json and use babel-minify, https://babeljs.io/docs/en/babel-minify
package.json
{
...
"scripts": : {
"minify": "minify wrapper.js --out-file wrapper.min.js --mangle.keepClassName"
}
...
}
Add entry object to your webpack.config.js.
module.exports={
entry: './src/wrapper.js',
...
}
webpack points the entry object by default to ./src/index.js.
So if you don't override entry object, webpack will bundle the file in ./src/index.js
Update
To point to a output directory properly
output: {
filename: 'wrapper.js',
path: path.resolve(__dirname, 'build')
}

Electron-Typescript: Bundling everything

I'm trying to create a web app using electron written in Typescript. I'm having problems when building my application. Specifically, I am not sure on how to combine: tsc (To convert my .ts file to .js) and then electron dist/main.js. Potentially, I want to run npm start which first compiles my .ts file and then run electron. Can anyone comment on what would be the best approach to achieve this?
Use ts-loader with webpack to bundle .ts files with config like below,
const path = require("path")
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
and then in your npm script include these,
{
"build-watch": "webpack -w",
"electron": "electon dist/main.js"
}
then start both using npm-run-all (or any other tool like concurrently),
npm-run-all start build-watch electron
I would suggest using https://webpack.electron.build/. It has instructions for adding typescript support here https://webpack.electron.build/add-ons#typescript

"webpack" vs "webpack --watch" creates different output

Im using this set up as the base of my project: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
When I run webpack, it compiles a bundle that works in the browser.
When I run webpack --watch, it re-compiles on file change, but causes this error in the browser:
Uncaught ReferenceError: exports is not defined
I looked at the output of both, and it looks like webpack --watch does not include the webpack bootstrap code or my modules - only the entry file transpiled.
webpack
Includes all of my modules in a single file, along with using webpacks own module require.
E.g: var io = __webpack_require__(20);
webpack --watch
Only includes my entry module - no other modules, no __webpack_require__.
E.g. var io = require("socket.io-client");
Versions:
- webpack: 3.7.1
- tsc: 1.8.10
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "bundle.js",
path: __dirname + "/dist"
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" },
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
The fix is to remove outDir from tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/"
}
}
It was the tsconfig.json file having a conflicting output directory. Files are only written by typescript when using webpack --watch

How to disable AMD on 4 files and load them in order with webpack

I need to disable AMD on 4 files and load video.js first before loading the other 3 files, because they depend on it. When I tried doing it in webpack.config.js like so:
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: __dirname + '/public',
filename: 'bundle.js'
},
devServer: {
inline: true,
contentBase: './src',
port: 3333
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules|lib/,
loader: 'babel',
query: {
presets: ['es2015', 'react', 'stage-2'],
plugins: ['transform-class-properties']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /[\/\\]lib[\/\\](video|playlist|vpaid|overlay)\.js$/,
exclude: /node_modules|src/
loader: 'imports?define=>false'
}
]
}
}
It doesn't really work, because it just loads video.js (with disabled AMD) and completely ignores the other 3 files.
My folder structure is like so:
▾ lib/
overlay.js
playlist.js
video.js
vpaid.js
▸ node_modules/
▾ public/
200.html
bundle.js
▾ src/
App.js
index.html
main.js
LICENSE
package.json
README.md
webpack.config.js
Now, I found something that takes me 1 step back, because now even video.js doesn't load:
require('imports?define=>false!../lib/video.js')
require('imports?define=>false!../lib/playlist.js')
require('imports?define=>false!../lib/vpaid.js')
require('imports?define=>false!../lib/overlay.js')
and instead just throws these kinds of warnings:
WARNING in ./~/imports-loader?define=>false!./lib/video.js
Critical dependencies:
15:415-422 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/video.js 15:415-422
WARNING in ./~/imports-loader?define=>false!./lib/playlist.js
Critical dependencies:
10:417-424 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/playlist.js 10:417-424
WARNING in ./~/imports-loader?define=>false!./lib/vpaid.js
Critical dependencies:
4:113-120 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/vpaid.js 4:113-120
WARNING in ./~/imports-loader?define=>false!./lib/overlay.js
Critical dependencies:
10:416-423 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/overlay.js 10:416-423
So, my question is, how can I make this work in webpack.config.js so that I don't get these warnings?
I have solved the problem! To make this work you need this:
{
test: /[\/\\]lib[\/\\](video|playlist|vpaid|overlay)\.js$/,
exclude: /node_modules|src/
loader: 'imports?define=>false'
}
and this
require('script-loader!../lib/video.js')
require('script-loader!../lib/playlist.js')
require('script-loader!../lib/vpaid.js')
require('script-loader!../lib/overlay.js')
together!
Now, if you use this (instead of script-loader):
require('imports?define=>false!../lib/video.js')
require('imports?define=>false!../lib/playlist.js')
require('imports?define=>false!../lib/vpaid.js')
require('imports?define=>false!../lib/overlay.js')
It's not gonna work! (you need both imports-loader and script-loader working in unison.

Webpack: node_modules/css/index.js didn't return a function

I'm trying out webpack for the first time and used this tutorial to get started and include react.js.
After finishing the steps and installing the style and css module I keep getting an error that the css module didn't return a function.
This is my index.jsx:
/** #jsx React.DOM */
'use strict';
require('../css/normalize.css');
var React = require('react');
var Hello = require('./Test/Hello');
React.render(<Hello />, document.getElementById('content'));
And my webpack config file:
module.exports = {
entry: './ui/src/index.jsx',
output: {
path: __dirname + '/build-ui',
filename: 'app.js', //this is the default name, so you can skip it
//at this directory our bundle file will be available
//make sure port 8090 is used when launching webpack-dev-server
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.scss$/,
loader: "style!css!sass"
}
]
},
externals: {
//don't bundle the 'react' npm package with our bundle.js
//but get it from a global 'React' variable
'react': 'React'
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};
When webpack tries to bundle the project it always states the following error:
ERROR in Loader /Users/Johannes/Documents/Development/holmes/node_modules/css/index.js didn't return a function
# ./ui/src/index.jsx 5:0-31
I don't know what to do about that. Has anyone encountered that issue? And how can I solve it?
EDIT: My directory looks as follows:
holmes/
ui/
css/
normalize.css
src/
Test/
Hello.jsx
index.jsx
index.html
package.json
webpack.config.js
This error is caused by a css module inside node_modules. Since you've specified the css-loader in your config, webpack tries to lookup that loader inside node_modules and finds another module called css which doesn't look like a loader (hence the error message).
To avoid confusion you should simply add the -loader postfix to each loader. Omitting the -loader postfix is just a convenience feature by webpack, but unfortunately it's the culprit of that error in your case.
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader"
}
Update: Starting with webpack 2, you can't omit the -loader postfix anymore. We decided to do this to prevent errors like this.
I had a similar issue with react-flexbox-grid. In my case, the solution was installing css-loader and style-loader npm modules:
npm install css-loader style-loader --save-dev
I also came across a similar issue using node-noop.
Fortunately, using null as a replacement worked when I added enzyme and react-addons-test-utils to a project.

Categories