Browserify external doesn't work - browserify

I'm trying to split a bundle on two parts. For example to move one package with all it's dependencies to separate bundle file.
To exclude package from main bundle I declare it as external:
browserify({
entries: ['./src/index.js'],
extensions: ['.js'],
debug: true
})
.external(['PdfKit']) // Specify all vendors as external source
.bundle()
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('dist/'));
The problem is that app.js contans full code of PdfKit package with all dependencies.
Full working demo awailable here: https://github.com/motz-art/browserify-external-test
How can I remove some (but not all) packages with all it's dependencies from app.js?

The external method is case sensetive. And must match package name as it appears inside require.
In my case 'PdfKit' is marked as external but index.js references 'pdfKit' so filter returns true, but than the package it self is resolved because windows is case insensetive.

Related

Npm workspaces: Different "main" property for development and publishing?

I've created an npm workspace with two packages "foo" and "bar".
Furthermore, I'm using typescript so both packages contain a src/index.ts.
During development, I want to have the "main" property of both packages to be src/index.ts.
But after building and publishing the packages the "main" entry has to point to the built dist/index.js.
How can I accomplish that or is my assumption wrong, that I can point to the typescript file during development?
But then I would have to rebuild the packages during development all the time.
I hope that's not necessary.
Thank you for your help in advance
UPDATE
To be more precise, I need to have "main" point to the Typescript file src/index.ts because otherwise, I can't reference "foo" inside of "foo" itself:
// foo/src/index.ts
import { something } from 'foo';
This error is thrown:
[vite:resolve] Failed to resolve entry for package "foo". The package may have incorrect main/module/exports specified in its package.json.
The above import only works, If "main" points to src/index.ts.
Otherwise I would have to use relative paths to the imported file of the same project, for example
// foo/src/index.ts
import { something } from './someotherfile.ts';
I found out, that vite needs the plugin vite-tsconfig-paths to find my main tsconfig.json to properly resolve the project:
// vite.config.ts
import tsconfigPaths from "vite-tsconfig-paths";
plugins: [
tsconfigPaths({
root: "../../",
}),
],

Webpack can not resolve module

I need some guidance. I am experiencing an issue where webpack throws an error that it can not find a module . I was trying to add a require statement of a package(included as dependency). I got it working in another project where I don't need webpack. The code looks basically as follows:
context.subscriptions.push(
vscode.commands.registerCommand("vstodo.helloWorld", () => {
vscode.window.showInformationMessage(
"test"
);
const sfdx = require('sfdx-node');
sfdx.auth.web.login({
setdefaultdevhubusername: true,
setalias: 'HubOrg'
})
.then(() => {
// Display confirmation of source push
console.log('Source pushed to scratch org');
});
}));
My webpack config can be found here
I uploaded a simplified version of the repository here Repository
containing all the configuration files for rollup and webpack.
If I leave out the part starting at the require statement everything works again.
Any help on how to tackle this would be much appreciated, thanks
The vscode extension page has a short troubleshooting guide about this: https://code.visualstudio.com/api/working-with-extensions/bundling-extension#webpack-critical-dependencies.
They suggest the following solutions:
Try to make the dependency static so that it can be bundled.
Exclude that dependency via the externals configuration. Also make sure that those JavaScript files aren't excluded from the packaged extension, using a negated glob pattern in .vscodeignore, for example !node_modules/mySpecialModule.

What code coverage tool to use for the javascript code in a Kotlin Multiplatform project?

I can use jacoco on the JVM side, but what can I use on the JS side of the Multiplatform project?
For now, there are no integrated code coverage tools.
But you can implement it manually using karma.config.d and https://karma-runner.github.io/0.8/config/coverage.html.
Note: you can do it only with browser target
How to setup:
Necessary to add dependencies, ideally dev dependencies into test source set, but dev dependencies are possible only since 1.4-M3, so they can be replaced with usual npm
implementation(devNpm("istanbul-instrumenter-loader", "3.0.1"))
implementation(devNpm("karma-coverage-istanbul-reporter", "3.0.3"))
After that create js file in karma.config.d folder in the project folder
;(function(config) { // just IIFE to protect local variabled
const path = require("path") // native Node.JS module
config.reporters.push("coverage-istanbul")
config.plugins.push("karma-coverage-istanbul-reporter")
config.webpack.module.rules.push(
{
test: /\.js$/,
use: {loader: 'istanbul-instrumenter-loader'},
include: [path.resolve(__dirname, '../module-name/kotlin/')] // here is necessary to use module-name in `build/js/packages`
}
)
config.coverageIstanbulReporter = {
reports: ["html"]
}
}(config));
It works with Kotlin code (but honestly report is arguable) but anyway, it provides both statistics for js and Kt files, but for js indicate 0%.
I created a feature request: https://youtrack.jetbrains.com/issue/KT-40460
Update:
The HTML file with results is in build/js/packages/{$module-name}-test/coverage/index.html. You can run build or browserTest task.
NOTE: If you on Windows you have to change include: [path.resolve(__dirname, '../module-name/kotlin/')] to include: [path.resolve(__dirname, '..\\module-name\\kotlin\\')]

Webpack 4 : ERROR in Entry module not found: Error: Can't resolve './src'

I was trying to run webpack-4 first time
webpack ./src/js/app.js ./dist/app.bundle.js
it shows warning / error :
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
ERROR in multi ./src/js/app.js ./dist/app.bundle.js
Module not found: Error: Can't resolve './dist/app.bundle.js' in 'D:\wamp64\www\webpack-4'
# multi ./src/js/app.js ./dist/app.bundle.js
Then i tried to change the mode
webpack --mode development
it shows :
ERROR in Entry module not found: Error: Can't resolve './src'
Resolved
Spent a lot of time to find out the solution.
Solution: Add index.js file into src folder.
That's it!.. solved :)
During Research, I found some facts about webpack 4 :
webpack 4 doesn’t need a configuration file by default!
webpack 4 there is no need to define the entry point: it will take ./src/index.js as the default!
Met this problem when deploying on now.sh
Solution: Use Default Behavior
Move entry point to src/index.js.
This leverage webpack#4 default value for entry:
By default its value is ./src/index.js, but you can specify a
different (or multiple entry points) by configuring the entry property
in the webpack configuration.
Solution: Be Specific
As #Lokeh pointed out, if you don't want to change your JS file location you can always use path.resolve() in your webpack.config.js:
entry: path.resolve(__dirname, 'src') + '/path/to/your/file.js',
Adding a context explicitly in webpack.config.js fixed issue for me. Adapt the following piece of code in your project:
context: __dirname + '/src',
entry: './index.js',
webpack ./src/js/app.js --output ./dist/app.bundle.js --mode development
This worked for me. I had the same trouble, it is because of a new version of webpack
webpack version 4.46.0
Perhaps someone gets stuck during migration from webpack 4 to 5.
in case of multiple webpack config files and if anyone uses merge:
Say webpack.common.js relies on some variables passed from cli eg:
module.export = (env) => {
const {myCustomVar} = env;
return {
// some common webpack config that uses myCustomVar
}
}
When you require common config in say webpack.prod.js:
const { merge } = require('webpack-merge'); // <-- `merge` is now named import if you are using > v5
const common = require('./webpack.common.js');
const getProdConfig = () => {....}
module.exports = (env) => {
return merge(common(env), getProdConfig()); // <-- here, `call` common as its exported as a fn()
};
I had a similar error and was able to resolve it with the command webpack src/index.js -o dist/bundle.js the -o did the trick. The issue wasn't the location of index.js it was missing the operator for defining the output path location.
See https://webpack.js.org/api/cli/
Version of webpack was 4.44.1
Other solutions didn't work. I solved this by adding this to package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack" //this
},
Then npm run build and it works. At first i've tried with npx webpack. Would love to know why it works.
Just leaving this here, incase someone is not paying attention to the details like me, I had the same error, but because my webpack config file was named webpack.config instead on webpack.config.js, so my custom configurations were never picked and webpack was falling back to the defaults entry "src/index.js"
As of webpack ^4.29.6 you don't need any configuration file so instead of giving path in package.json we need to write simply "build": "webpack" and keep index.js as entry point in src folder. However if you want to change entry point you can do so in webpack config file
For Rails 6 application this steps worked for me:
1) bundle exec rails webpacker:install
system will reinstall webpacker but will rewrite few files:
modified: config/webpack/environment.js
modified: config/webpacker.yml
modified: package.json
modified: yarn.lock
2) Return configs to initial state:
git checkout config/webpack/environment.js
git checkout config/webpacker.yml
package.json and yarn.lock you can leave as they are
Spent a lot of time similarly to others to get around this annoying problem. Finally changed webpack.config.js as follows:-
output: {
path: path.resolve(__dirname, './src'), //src instead of dist
publicPath: '/src/', //src instead of dist
filename: 'main.js' //main.js instead of build.js
}
...as Edouard Lopez and Sabir Hussain mentioned that you don't need to mention an entry point, removed that also and the app compiled after a long frustration.
So my problem, which I would wager is a lot of people's problem is that I set the entry path based on my whole app root. So in my case, it was /client/main.ts. But because my webpack.config.js file was actually inside /client, I had to move into that folder to run webpack. Therefore my entry was now looking for /client/client/main.ts.
So if you get this error you need to really look at your entry path and make sure it is right based on where you are running webpack and where your webpack.config.js file is. Your entry path needs to be relative to where you are running webpack. Not relative to your app root.
I had this problem when changing between React/Rails gems. Running rails webpacker:install restored me to the Rails webpacker defaults, but also overwrote all of my config files. Upon closer inspection, the culprit turned out to be my webpack/development.js file, which in a previous gem version had gotten modified from this Rails webpacker default:
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const environment = require('./environment')
module.exports = environment.toWebpackConfig()
Once I restored the file to those contents, this error went away. Specifically I had been missing the module.exports = environment.toWebpackConfig() line, which apparently is pretty important for those who want to avoid Rails webpacker thinking it needs a src/index.js file (it doesn't)

Aurelia javascript dependencies loading time [duplicate]

I wrote a minimal test page to try out Aurelia.
http://www.andrewgolightly.com/
GitHub: https://github.com/magician11/ag-landingpage
My last test, showed it took 55 seconds to load the page with 135 requests.
It seems I need to bundle the jspm_packages directory first so that the 543KB gets downloaded at once.. and not in pieces.
So given I followed this example: http://aurelia.io/get-started.html
How do I bundle the packages? It's not clear to me from https://github.com/jspm/jspm-cli/wiki/Production-Workflows
And then what do I update in my index.html file? And I'll still need to include the jspm_packages folder as I reference it in the head, right?
<link rel="stylesheet" href="jspm_packages/github/twbs/bootstrap#3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="jspm_packages/npm/font-awesome#4.3.0/css/font-awesome.min.css">
Thanks.
Update
The team is working on bundling..
From Rob Eisenberg: "We aren’t finished with our bundling support just yet. We’re working on it."
This question was posted at a very early time but we do have a strategy now in place that works with jspm and system.js loader for bundling. As a note it's not that the framework is slow it's that the loading of assets was taking a while early on due to the high number of requests (and that you probably didn't have gzip enabled)
I've copied this from my blog post on the subject - http://patrickwalters.net/my-best-practices-for-aurelia-bundling-and-minification/
Requirements
Understand that a jspm bundle command is used to let system.js, our module loader, know to load the bundle
Understand this only covers the JavaScript files (for now)
Create a new bundle
Open your terminal and navigate to your skeleton-navigation folder.
Open your config.js in your text editor
Run this command -
jspm bundle '*' + aurelia-skeleton-navigation/* + aurelia-bootstrapper + aurelia-http-client + aurelia-dependency-injection + aurelia-router dist/app-bundle.js --inject --minify
Breakdown
// Create a bundle
jspm bundle
// Bundle all of these paths
// from my config.js
'*' +
aurelia-skeleton-navigation/* +
aurelia-bootstrapper +
aurelia-http-client +
aurelia-dependency-injection +
aurelia-router
// Create the bundle here
// with this name
dist/app-bundle.js
// These modifiers tell the bundle
// to both minify and then inject
// the bundle
--inject
--minify
Additional notes on bundling
If you are serving in production you may want to look at setting baseUrl in your config.js like that
To unbundle and serve files individually use jspm unbundle
Since we used the --inject modifier system.js should pick up on our bundle and serve it without changing our script path in index.html
You can add more files by using + {filename} in the bundle area
2016 Update
The official toolkit for bundling aurelia applications can be installed via npm using npm install --save-dev aurelia-bundler.
Once installed, you can set up a gulp task for handling the bundle / unbundle process. A basic example of a task looks like this:
build/tasks/bundle.js
var gulp = require('gulp');
var bundler = require('aurelia-bundler');
var config = {
bundles: {
'dist/app-build': {
includes: [
'**/*.js'
],
options: {
minify: true
}
}
}
};
gulp.task('bundle', ['build', 'unbundle'], function() {
return bundler.bundle(config);
});
gulp.task('unbundle', function() {
return bundler.unbundle(config);
});
I've written a more in-depth article here: http://www.foursails.co/blog/aurelia-bundling/
The official documentation can be found here: https://github.com/aurelia/bundler
There is a GitHub repository that includes an r.js bundling strategy for the Aurelia AMD target build, as well as sample projects for using the bundle in Visual Studio with TypeScript (including an aurelia.d.ts TypeScript type definition file).
repo
bundling with r.js
aurelia.d.ts
using this strategy should dramatically reduce your load time as it will be loading one file instead of many files.