Does anyone know how to create multiple output paths in a webpack.config.js file? I'm using bootstrap-sass which comes with a few different font files, etc. For webpack to process these i've included file-loader which is working correctly, however the files it outputs are being saved to the output path i specified for the rest of my files:
output: {
path: __dirname + "/js",
filename: "scripts.min.js"
}
I'd like to achieve something where I can maybe look at the extension types for whatever webpack is outputting and for things ending in .woff .eot, etc, have them diverted to a different output path. Is this possible?
I did a little googling and came across this *issue on github where a couple of solutions are offered, edit:
but it looks as if you need to know the entry point in able to specify an output using the hash method
eg:
var entryPointsPathPrefix = './src/javascripts/pages';
var WebpackConfig = {
entry : {
a: entryPointsPathPrefix + '/a.jsx',
b: entryPointsPathPrefix + '/b.jsx',
c: entryPointsPathPrefix + '/c.jsx',
d: entryPointsPathPrefix + '/d.jsx'
},
// send to distribution
output: {
path: './dist/js',
filename: '[name].js'
}
}
*https://github.com/webpack/webpack/issues/1189
however in my case, as far as the font files are concerned, the input process is kind of abstracted away and all i know is the output. in the case of my other files undergoing transformations, there's a known point where i'm requiring them in to be then handled by my loaders. if there was a way of finding out where this step was happening, i could then use the hash method to customize output paths, but i don't know where these files are being required in.
Webpack does support multiple output paths.
Set the output paths as the entry key. And use the name as output template.
webpack config:
entry: {
'module/a/index': 'module/a/index.js',
'module/b/index': 'module/b/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
}
generated:
└── module
├── a
│ └── index.js
└── b
└── index.js
I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.
But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js).
var config = {
// TODO: Add common Configuration
module: {},
};
var fooConfig = Object.assign({}, config, {
name: "a",
entry: "./a/app",
output: {
path: "./a",
filename: "bundle.js"
},
});
var barConfig = Object.assign({}, config,{
name: "b",
entry: "./b/app",
output: {
path: "./b",
filename: "bundle.js"
},
});
// Return Array of Configurations
module.exports = [
fooConfig, barConfig,
];
If you have common configuration among them, you could use the extend library or Object.assign in ES6 or {...} spread operator in ES7.
You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –
module.exports = {
entry: {
home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
}
};
If you can live with multiple output paths having the same level of depth and folder structure there is a way to do this in webpack 2 (have yet to test with webpack 1.x)
Basically you don't follow the doc rules and you provide a path for the filename.
module.exports = {
entry: {
foo: 'foo.js',
bar: 'bar.js'
},
output: {
path: path.join(__dirname, 'components'),
filename: '[name]/dist/[name].bundle.js', // Hacky way to force webpack to have multiple output folders vs multiple files per one path
}
};
That will take this folder structure
/-
foo.js
bar.js
And turn it into
/-
foo.js
bar.js
components/foo/dist/foo.js
components/bar/dist/bar.js
Please don't use any workaround because it will impact build performance.
Webpack File Manager Plugin
Easy to install copy this tag on top of the webpack.config.js
const FileManagerPlugin = require('filemanager-webpack-plugin');
Install
npm install filemanager-webpack-plugin --save-dev
Add the plugin
module.exports = {
plugins: [
new FileManagerPlugin({
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}),
],
};
Screenshot
If it's not obvious after all the answers you can also output to a completely different directories (for example a directory outside your standard dist folder). You can do that by using your root as a path (because you only have one path) and by moving the full "directory part" of your path to the entry option (because you can have multiple entries):
entry: {
'dist/main': './src/index.js',
'docs/main': './src/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './'),
}
This config results in the ./dist/main.js and ./docs/main.js being created.
In my case I had this scenario
const config = {
entry: {
moduleA: './modules/moduleA/index.js',
moduleB: './modules/moduleB/index.js',
moduleC: './modules/moduleB/v1/index.js',
moduleC: './modules/moduleB/v2/index.js',
},
}
And I solve it like this (webpack4)
const config = {
entry: {
moduleA: './modules/moduleA/index.js',
moduleB: './modules/moduleB/index.js',
'moduleC/v1/moduleC': './modules/moduleB/v1/index.js',
'moduleC/v2/MoculeC': './modules/moduleB/v2/index.js',
},
}
You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.
In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:
const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
// ...
new FileManagerPlugin({
onEnd: {
copy: [{
source: './dist/*.*',
destination: './public/',
}],
},
}),
],
You can only have one output path.
from the docs https://github.com/webpack/docs/wiki/configuration#output
Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified.
If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPlugin or recordsPath.
I wrote a plugin that can hopefully do what you want, you can specify known or unknown entry points (using glob) and specify exact outputs or dynamically generate them using the entry file path and name. https://www.npmjs.com/package/webpack-entry-plus
I actually wound up just going into index.js in the file-loader module and changing where the contents were emitted to. This is probably not the optimal solution, but until there's some other way, this is fine since I know exactly what's being handled by this loader, which is just fonts.
//index.js
var loaderUtils = require("loader-utils");
module.exports = function(content) {
this.cacheable && this.cacheable();
if(!this.emitFile) throw new Error("emitFile is required from module system");
var query = loaderUtils.parseQuery(this.query);
var url = loaderUtils.interpolateName(this, query.name || "[hash].[ext]", {
context: query.context || this.options.context,
content: content,
regExp: query.regExp
});
this.emitFile("fonts/"+ url, content);//changed path to emit contents to "fonts" folder rather than project root
return "module.exports = __webpack_public_path__ + " + JSON.stringify( url) + ";";
}
module.exports.raw = true;
u can do lik
var config = {
// TODO: Add common Configuration
module: {},
};
var x= Object.assign({}, config, {
name: "x",
entry: "./public/x/js/x.js",
output: {
path: __dirname+"/public/x/jsbuild",
filename: "xbundle.js"
},
});
var y= Object.assign({}, config, {
name: "y",
entry: "./public/y/js/FBRscript.js",
output: {
path: __dirname+"/public/fbr/jsbuild",
filename: "ybundle.js"
},
});
let list=[x,y];
for(item of list){
module.exports =item;
}
The problem is already in the language:
entry (which is a object (key/value) and is used to define the inputs*)
output (which is a object (key/value) and is used to define outputs*)
The idea to differentiate the output based on limited placeholder like '[name]' defines limitations.
I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.
All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.
Vinod Kumar's good workaround is:
module.exports = {
plugins: [
new FileManagerPlugin({
events: {
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}
}),
],
};
Related
I have 2 rollup config files which has some common parts and uncommon parts:
// rollup.config.umd.js
export config {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp',
output: {
file: 'my.comp.umd.js'
format: 'umd'
}...
and another file
// rollup.config.esm5.js
export config {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp',
output: {
file: 'my.comp.es5.js'
format: 'es'
}...
How do I keep these config files DRY ?
Not keeping DRY has following problems e.g. Imagine many external dependencies - if one forgets to add a new dependency in one place we are in trouble.
(I also use some different set of plugins etc and plugin configs but say that is out of scope of this problem.)
Firstly, they're just JavaScript modules, so you can always do this sort of thing:
// rollup.config.common.js
export default {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp'
};
// rollup.config.esm5.js
import common from './rollup.config.common.js';
export default Object.assign({
output: {
file: 'my.comp.es5.js'
format: 'es'
}
}, common);
// rollup.config.umd.js
import common from './rollup.config.common.js';
export default Object.assign({
output: {
file: 'my.comp.umd.js'
format: 'umd'
}
}, common);
But the real answer here is to combine the two configs into a single one like so:
export default {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp',
output: [
{
file: 'my.comp.es5.js'
format: 'es'
},
{
file: 'my.comp.umd.js'
format: 'umd'
}
]
};
As well as being simpler and easier to maintain, this will be faster, because Rollup can save doing a lot of the work twice.
If you need to change more than the output option between builds, you can also export an array of configs from a single file (export default [...]).
I am using Webpack 2 in my project to transpile and bundle ReactJS files along with a few other tasks. Here's what my config looks like:
var webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var config = {
module: {
loaders: [
{
exclude: /(node_modules)/,
loader: "babel-loader",
query: {
presets: ["es2015", "react"]
}
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "sass-loader"]
})
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
new ExtractTextPlugin({
filename: "../../public/dist/main.css"
})
],
};
var indexConfig = Object.assign({}, config, {
name: "index",
entry: "./public/javascripts/build/index.js",
output: {
path: __dirname + "/public/dist",
filename: "index.min.js",
},
});
var aboutConfig = Object.assign({}, config, {
name: "about",
entry: "./public/javascripts/build/about.js",
output: {
path: __dirname + "/public/dist",
filename: "about.min.js"
},
});
// Return Array of Configurations
module.exports = [
indexConfig, aboutConfig
];
As evident, I am using multiple build configurations for JS, one for each page. Now, I need to add some Bootstrap JS to the mix for which I also need JQuery and Tether. Thus, I have the following 3 files in my library folder:
jquery-3.2.1.min.js
tether.min.js
bootstrap.min.js
I need these 3 files to be concatenated and bundled along with the main JS files being emitted by Webpack (e.g., index.min.js, etc.). To do so, I modified my entry item thus:
entry: {
a: "./public/javascripts/lib/jquery-3.2.1.min.js",
b: "./public/javascripts/lib/tether.min.js",
b: "./public/javascripts/lib/bootstrap.min.js",
c: "./public/javascripts/build/index.js"
}
However, doing so throws the following error:
ERROR in chunk a [entry]
index.min.js
Conflict: Multiple assets emit to the same filename index.min.js
ERROR in chunk b [entry]
index.min.js
Conflict: Multiple assets emit to the same filename index.min.js
ERROR in chunk c [entry]
index.min.js
Conflict: Multiple assets emit to the same filename index.min.js
Obviously this is because Webpack is expecting multiple output files for multiple entry items. Is there any way to overcome this problem? An existing question illustrating a similar problem doesn't seem to have any acceptable answer at the moment.
UPDATE:
Tried using the Commons chunk plugin as suggested by terales, but Webpack threw the following error this time:
ERROR in multi jquery tether bootstrap
Module not found: Error: Can't resolve 'jquery' in '/home/ubuntu/panda'
# multi jquery tether bootstrap
ERROR in multi jquery tether bootstrap
Module not found: Error: Can't resolve 'tether' in '/home/ubuntu/panda'
# multi jquery tether bootstrap
ERROR in multi jquery tether bootstrap
Module not found: Error: Can't resolve 'bootstrap' in '/home/ubuntu/panda'
# multi jquery tether bootstrap
ERROR in chunk vendor [entry]
index.min.js
Conflict: Multiple assets emit to the same filename index.min.js
Your libs shouldn't be entries. They called "vendors" in Webpack's terms.
See minimum working example repo.
In your code you should implicitly extract common vendor chunk:
var config = {
entry: { // <-- you could make two entries
index: './index.js', // in a more Webpack's way,
about: './about.js' // instead of providing array of confings
},
output: {
filename: '[name].min.js',
path: __dirname + '/dist'
},
module: {
loaders: [
// Fix error 'JQuery is not defined' if any
{ test: require.resolve("jquery"), loader: "expose-loader?$!expose-loader?jQuery" },
]
},
plugins: [
// this assumes your vendor imports exist in the node_modules directory
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
return module.context && module.context.indexOf('node_modules') !== -1;
}
})
]
};
I am trying to run my webpack config file (see below), but I am still getting certain type of errors that reffers to a paths I use in my webpack settings:
- config.context
- config.module.rules
- config.output
My idea was, that I set up my config.context path absolutely (as it is written in docs), otherwise my webpack.config files reffers to node_modules in parents directory. But still, when I run webpack -w --env.dev command, it throws following errors:
It seems to me, that config.context cant handle absolute path as it should. Any help how to set up paths correctly? Thank you!
My webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractText = require('extract-text-webpack-plugin');
module.exports = function (env) {
var project = {
env: env.prod ? 'prod' : 'dev',
jsBase: './routesMap/',
cssBase: './src/css/'
}
var config = {
context: path.resolve(__dirname),
entry: {
'routesMap': project.jsBase + 'main.js'
},
output: {
path: path.join(__dirname, '/dist'),
filename: '[name].js'
},
plugins: [
new ExtractText({
filename: 'styles.min.css',
disable: false,
allChunks: true
})
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: path.join(__dirname, '/routesMap'),
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['es2015'],
plugins: ["transform-runtime"]
}
}
]
}
};
return config;
}
That's an issue with the latest webpack version. Try using uppercase drive letters in shell, e.g. C:/ instead c:/.
More info https://github.com/webpack/webpack/issues/4530.
I uninstalled latest webpack version (I had webpack 2.3.0) and installed version of 2.2.0, problem solved! As #zemirco stated in his answer, it has something to do with casesensitive letters in absolute path. Unfortunatelly changing small letter to big one doesnt help for me, so I just changed webpack version.
According to Swagger 2.0 specs, it might be possible to do this. I am referencing PathObject using $ref which points to another file. We used to be able to do this nicely using Swagger 1.2. But Swagger-UI does not seem to be able to read the referred PathObject in another file.
Is this part of spec too new and is not yet supported? Is there a way to split each "path"'s documentation into another file?
{
"swagger": "2.0",
"basePath": "/rest/json",
"schemes": [
"http",
"https"
],
"info": {
"title": "REST APIs",
"description": "desc",
"version": "1.0"
},
"paths": {
"/time": {
"$ref": "anotherfile.json"
}
}
}
To support multiple files, your libraries have to support dereferencing the $ref field. But I would not recommend to deliver the swagger file with unresolved references. Our swagger defintion has around 30-40 files. Delivering them via HTTP/1.1 could slow down any reading application.
Since we are building javascript libs, too, we already had a nodejs based build system using gulp. For the node package manager (npm) you can find some libraries supporting dereferencing to build one big swagger file.
Our base file looks like this (shortened):
swagger: '2.0'
info:
version: 2.0.0
title: App
description: Example
basePath: /api/2
paths:
$ref: "routes.json"
definitions:
example:
$ref: "schema/example.json"
The routes.json is generated from our routing file. For this we use a gulp target implementing swagger-jsdoc like this:
var gulp = require('gulp');
var fs = require('fs');
var gutil = require('gulp-util');
var swaggerJSDoc = require('swagger-jsdoc');
gulp.task('routes-swagger', [], function (done) {
var options = {
swaggerDefinition: {
info: {
title: 'Routes only, do not use, only for reference',
version: '1.0.0',
},
},
apis: ['./routing.php'], // Path to the API docs
};
var swaggerSpec = swaggerJSDoc(options);
fs.writeFile('public/doc/routes.json', JSON.stringify(swaggerSpec.paths, null, "\t"), function (error) {
if (error) {
gutil.log(gutil.colors.red(error));
} else {
gutil.log(gutil.colors.green("Succesfully generated routes include."));
done();
}
});
});
And for generating the swagger file, we use a build task implementing SwaggerParser like this:
var gulp = require('gulp');
var bootprint = require('bootprint');
var bootprintSwagger = require('bootprint-swagger');
var SwaggerParser = require('swagger-parser');
var gutil = require('gulp-util');
var fs = require('fs');
gulp.task('swagger', ['routes-swagger'], function () {
SwaggerParser.bundle('public/doc/swagger.yaml', {
"cache": {
"fs": false
}
})
.then(function(api) {
fs.writeFile('public/doc/swagger.json', JSON.stringify(api, null, "\t"), function (error) {
if (error) {
gutil.log(gutil.colors.red(error));
} else {
gutil.log("Bundled API %s, Version: %s", gutil.colors.magenta(api.info.title), api.info.version);
}
});
})
.catch(function(err) {
gutil.log(gutil.colors.red.bold(err));
});
});
With this implementation we can maintain a rather large swagger specification and we are not restricted to special programming language or framework implementation, since we define the paths in the comments to the real routing definitions. (Note: The gulp tasks are split in multiple files too.)
While it would theoretically be possible to do that in the future, the solution is still not fully baked into the supporting tools so for now I'd highly recommend keeping it in one file.
If you're looking for a way to manage and navigate the Swagger definition, I'd recommend using the YAML format of the spec, where you can add comments and that may ease up navigation and splitting of a large definition.
You can also use JSON Refs library to resolve such multi-file Swagger spec.
I've written about it in this blog post
There is also this GitHub repo to demonstrate how all of this work.
My solution to this problem is using this package below to solve the reference issue
https://www.npmjs.com/package/json-schema-ref-parser
Here is the code snippet when generating the swagger UI using that library. I was using Express.js for my node server.
import express from 'express';
import * as path from 'path';
import refParser from '#apidevtools/json-schema-ref-parser';
import swaggerUi from 'swagger-ui-express';
const port = 3100;
const app = express();
app.get('/', async (req, res) => {
res.redirect('/api-docs')
});
app.use(
'/api-docs',
async function (req: express.Request, res: express.Response, next: express.NextFunction) {
const schemaFilePath = path.join(__dirname, 'schema', 'openapi.yml');
try {
// Resolve $ref in schema
const swaggerDocument = await refParser.dereference(schemaFilePath);
(req as any).swaggerDoc = swaggerDocument;
next();
} catch (err) {
console.error(err);
next(err);
}
},
swaggerUi.serve,
swaggerUi.setup()
);
app.listen(port, () => console.log(`Local web server listening on port ${port}!`));
Take a look at my Github repository to see how it works
my app has directory as follows
app -> appName -> index.html (js,css)
and for some reason, this appName wrapper folder is messing up wiredire
{ dest: '.tmp/concat/scripts/vendor.js',
src:
[ '../bower_components/es5-shim/es5-shim.js',
'../bower_components/angular/angular.js',
'../bower_components/json3/lib/json3.js',
'../bower_components/angular-resource/angular-resource.js',
'../bower_components/angular-cookies/angular-cookies.js',
'../bower_components/angular-sanitize/angular-sanitize.js',
'../bower_components/angular-animate/angular-animate.js',
'../bower_components/angular-touch/angular-touch.js',
'../bower_components/angular-route/angular-route.js' ] },
this is what would've been produced if directory is as follows
app -> index.html(js,css)
{ dest: '.tmp/concat/scripts/vendor.js',
src:
[ 'bower_components/es5-shim/es5-shim.js',
'bower_components/angular/angular.js',
'bower_components/json3/lib/json3.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-route/angular-route.js' ] },
and wiredep does change the index.html's script content and how can I control that flow? sometimes its stripping out angular-sanitize from its script[src]
You Should use the replace option of wiredep:
wiredep(
{
fileTypes: {
html: {
replace: {
js: '<script src="/app/appName/{{filePath}}"></script>'
}
}
}
})
Will generate:
<script src="/app/appName/bower_components/angular/angular.js"></script>
This is my gulp setup (same principle apply to Grunt, just pass the same options to it).
gulp.task('wiredep' , function()
{
return gulp.src('./app/index.html')
.pipe(wiredep({
'ignorePath': '../'
}))
.pipe(gulp.dest('./app'));
});
You can look at the wiredep source code in the lib/inject-dependencies.js (line:80~85)
map(function (filePath) {
return $.path.join(
$.path.relative($.path.dirname(file), $.path.dirname(filePath)),
$.path.basename(filePath)
).replace(/\\/g, '/').replace(ignorePath, '');
}).
It just replace the bit you supply (or not if you don't give it one).
Hope that helps.
Have you tried adding cwd to the options block?
Ex:
// Automatically inject Bower components into the app
wiredep: {
options: {
cwd: 'app/appName'
}
....
}