Webpack 2: CommonsChunkPlugin issue - webpack-2

I would like to ask a question about CommonsChunkPlugin
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
vendor: ['moment'],
app: ['./www/build/main.js']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'chunk'
})
]
}
After i run the webpack script, there are 3 files generated (vendor.bundle, app.bundle, chunk.bundle). My questions are:
What is the usage chunk.bundle and why it is generated? I set the config in "entry" and output is depends on the [name] of entry
How can i run the script to all files under a folder? The current setting needs to input one by one.
If my file is too large, how can i split is into some smaller files?
Thanks.

1) The chunk.bundle.js is being generated by the plugin. It operates a little outside of the usual Webpack flow.
2) Not sure what you're getting at, here. You probably need to look at the minChunks setting, or chunks.
3) You can use multiple instances of the plugin. I've found that you have to use the chunks setting on every instance except for one to avoid getting an error. Basically that specifies on what entry files the plugin will operate. You can specify all your entry files in chunks, and then use a function with minChunks to filter out what you want to include in that file.

Related

Plugin strip ~ How to exclude a specific file whose extension was included generally?

I'm using the rollup plugin strip to exclude the console.logs in the production built with following settings
plugins: [
strip({
include: ['**/*.(js|svelte)'],
labels: ['dev'],
functions: ['console.log'],
})
]
I now have the situation that I would like to keep one special log in production. So I created a function in a new file logInProduction.js
export function logInProduction(msg) {
console.log(msg)
throw new Error('PRODUCTION')
}
and added the file to the plugin options by adding this line
exclude: ['logInProduction.js'],
But when calling the function, the error is thrown, so the function was called, but the log before doesn't appear.
Is this because the .js ending is generally included before so the specific exclusion doen't have any effect? Is it possible to do this?
Or is there another maybe better way to keep one specific console.log?
Problem was, that the filename was missing the directory, so
exclude: ['src/utils/logInProduction.js'],
or
exclude: ['**/logInProduction.js'],
does work

I'm getting an error building a sveltekit project

I'm building a sveltekit project. One thing I've done is created a custom type of file which is converted to a *.svelte file upon building or running the development server. By default, sveltekit includes the rollup extension rollup-plugin-dynamic-import-variables which is trying to parse my custom file (who knows why?) and throwing an "unexpected token" error. I'm trying to configure that extension to ignore my custom files, but so far without success. Here is my attempted svelte.config.js file:
// #type {import('#sveltejs/kit').Config}
var config;
import adapter from '#sveltejs/adapter-static';
import dynamicImportVariables from 'rollup-plugin-dynamic-import-variables';
config = {
kit: {
// --- hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
adapter: adapter({
pages: 'build',
assets: 'build',
fallback: null
}),
vite: {
plugins: [
dynamicImportVariables({
warnOnError: true,
exclude: '**'
})
]
}
}
};
export default config;
To be honest about it, I don't use dynamic imports anywhere and therefore would accept as a solution the complete disabling of the extension. But anything that would get it to ignore my custom files would also work.
UPDATE: SvelteKit 1.0.0-beta now requires pages/endpoints to follow a specific naming pattern, so explicit file exclusion should no longer be needed.
SvelteKit specially handles files in the routes/ directory with the following filenames (note the leading + in each filename):
+page.svelte
+page.js
+page.server.js
+error.js
+layout.svelte
+layout.js
+layout.server.js
+server.js
All other files are ignored and can be colocated in the routes/ directory.
If, for some reason, you need to have a file that has a special name shown above, it's currently not possible to exclude that file from special processing.
Original outdated answer:
The rollup-plugin-dynamic-import-variables is actually included by Vite. To configure Vite's plugin, set the build.dynamicImportVarsOptions property:
// svelte.config.js
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
// hydrate the <div id="svelte"> element in src/app.html
target: "#svelte",
vite: {
build: {
dynamicImportVarsOptions: {
exclude: [/node_modules/, /\.starbucks$/],
},
},
},
},
}
export default config
But that's not going to fix the problem...
SvelteKit processes all files under src/routes/ so that they're automatically imported in the output application (in .svelte-kit/build/app.js), which will result in the same error.
Option 1: Private modules
You could exclude a src/routes/*.starbucks file by making it a private module, which has a leading underscore in the filename:
src/routes/_home.starbucks 👈
src/routes/_index.starbucks 👈
src/routes/index.svelte
Option 2: Move files outside src/routes
Alternatively, move those *.starbucks files outside of src/routes/ (e.g., into src/starbucks/ or src/lib/):
src/routes/index.svelte
src/starbucks/home.starbucks 👈
src/starbucks/index.starbucks 👈
src/lib/home.starbucks 👈
src/lib/index.starbucks 👈

How do I add an additional postcss plugin via the new #angular/cli v7 angular.json or custom-webpack.config.js?

#angular/cli#7+ allows a customWebpackConfig to be specified to provide custom webpack configuration, such as:
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./build/custom-webpack.config.js",
"mergeStrategies": {
"externals": "prepend"
}
},
...
This file then technically allows you to prepend, append or replace any portion of the webpack configuration. Prior to upgrading to #angular#7.1.3 and #angular/cli#7.1.3 we had ejected the webpack configuration to make some additions. One such addition was the postcss-momentum-scrolling postcss-loader plugin that automatically enabled iOS momentum scrolling on all scrollable containers.
I am seeking support on figuring out how to generate the necessary custom webpack code to load this plugin via the supported customizations allowed by #angular/cli#7+.
Here is a sample of what I have tried in my custom-webpack.config.js file:
const postcssMomentumScrolling = require('postcss-momentum-scrolling');
module.exports = {
module: {
rules: [
{
test: /\.scss$|\.sass$/,
use: [
{
"loader": "postcss-loader",
"options": {
"plugins": [
postcssMomentumScrolling(),
]
}
}
]
},
],
},
};
As soon as I touch the scss chunk of the webpack config, it seems to do a replace instead of a merge or prepend, breaking the build.
I am wondering if anyone has a guide or suggestions on how to see what the initial webpack configuration that #angular/cli generates that is the starting point for modifications and a way to preview/peek at the code to be executed as debugging.
Also, an example of a similar customization would be great.
Thanks!
I think you need to tell to "customWebpackConfig" which portion to merge. Like this:
"mergeStrategies": {
"module.rules": "prepend"
}
In this way you're going to tell to merge with prepend strategy.
According to "custom-webpack" documentation it should default to "append" which doesn't seem the case in your example.
It's been a while since you've put the question but I wanted to actually ask if you have been able to fix it since I'm running in some issues getting my "module.rules" merged...it seems to work only if I set "replace" strategy.

Ignore / prevent emit of a particular file in wepack

Is there a way to prevent a specific file from being emitted to the output in Webpack (2)?
I'm using html-webpack-plugin and when building for the backend CMS, I'd like to avoid emitting the html file but still emit its meta image dependencies.
this might help: ignore-emit-webpack-plugin
it allows you to ignore emitted files by patterns
// webpack config
const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');
module.exports = {
// ...
plugins: [ new IgnoreEmitPlugin(/unwanted-file\.html$/) ]
// ...
};
disclosure - i'm the author

Gulp task to bundle bower_components?

I'd appreciate it so much if someone could please tell me a good way to handle bundling bower components. I feel like I've tried everything... Although, I can't seem to find any gulp tasks that handle this already. Could it really not exist?
Let's say it doesn't exist. Worst case scenario is I have to specify the paths of each "dist" file from bower_components folder. (It is annoying that each component seems to have its own "dist" folder... nothing is standardized.)
So even if I do that, I've noticed some components like 'active-support' seem to have require('lodash') and such in them. I think that if I just simply copy that file, it will break because the requires won't resolve.
What am I missing? How do I simply take all bower_components and bundle into a "common.js"... is there a way or is it a clusterfluck?
Update
As pointed out by Alerty, the new Gulp policy seems to be: use bower directly and glob patterns (and hope that the packages maintainers have a proper "ignore" properties).
Previously
You can use main-bower-files or gulp-bower-src to get files from your bower components. They can also use "ignore" or "main" overrides in your own bower file.
This is how I managed it (but see gulpfile.js for project structure, it's not a single gigantic gulpfile) :
https://github.com/notbrain/viceroy/blob/master/gulp/tasks/bower.js
Would be a bit more modular to simply concat all bower deps and then do the uglify() and minifyCSS() tasks separately on dist/ source locations, based on dev/prod env targets, but will have to wait for future updates.
Use main-bower-files:
var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
gulp.task('TASKNAME', function() {
return gulp.src(mainBowerFiles())
.pipe(/* what you want to do with the files */)
});
if you have folders like:
-app
-bower
-node_modules
Gulpfile.js
package.json
the solution are:
gulp.task("connect", function () {
connect.server({
root: ["app"],
livereload: true,
port: 8034,
middleware: function (connect) {
return [connect().use("/bower", connect.static("bower"))];
}
});
});
If your project use AMD specification.
You can use gulp-edp bundle the modules.
set module info at module.conf
{
"baseUrl": "src",
"paths": {},
"packages": [
{
"name": "etpl",
"location": "../bower_components/etpl/3.0.1/src",
"main": "main"
},
{
"name": "jquery",
"location": "../bower_components/jquery/1.9.1/src",
"main": "jquery.min"
}
],
"combine": {
"app": true
}
}
gulpfile.js
var gulp = require('gulp');
var edp = require('gulp-edp');
gulp.src(
[
'src/**/*.js'
'bower_components/**/*.js',
'!bower_components/**/{demo,demo/**}',
'!bower_components/**/{test,test/**}'
]
)
.pipe(edp({
getProcessors: function () {
var moduleProcessor = new this.ModuleCompiler();
return [moduleProcessor];
}
}))
.pipe(gulp.dest('dist'));
See EDP wiki for more features.

Resources