I have 2 files, a.js and b.js:
a.js:
function hello() {
alert('hey');
alert('bye');
}
b.js:
const name = 'Bob';
alert(name)
I import them both in my entry file:
import './a';
import './b';
I want to combine them, my webpack.config.js looks like this:
const path = require('path');
module.exports = {
entry: './entry.js',
mode: 'production',
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
};
When I run webpack I get a module:
// etc...
/***/ (function(module, exports) {
function hello() {
alert('hey');
alert('bye');
}
/***/ }),
/* 2 */
/***/ (function(module, exports) {
const name = 'Bob';
alert(name)
/***/ })
/******/ ]);
Instead how can I just get:
function hello() {
alert('hey');
alert('bye');
}
const name = 'Bob';
alert(name)
This plugin does what I want to achieve but there is a bug where I can't minify the combined file, on top of that I would also like to run babel to transform the code to be es5 compatible. All these things seem to be a lot easier to do the regular webpack way so it would be great if I can just get webpack to export a normal script instead of a module..
I ended up using gulp for this, it was pretty simple. Here's what my gulpfile.js looks like:
const gulp = require('gulp');
const { watch } = require('gulp');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
const terser = require('gulp-terser');
const defaultTask = (cb) => {
return gulp
.src([
'src/file1.js',
'src/file2.js',
'src/file3.js',
// etc...
])
.pipe(concat('bundle.min.js'))
.pipe(
babel({
presets: ['@babel/preset-env']
})
)
.pipe(terser())
.pipe(gulp.dest('dist'));
cb();
};
exports.default = defaultTask;
This will concatenate, minify and transpile es6 to es5 and save the output in dist/bundle.min.js
as is without changing the script to a module.
You can do this by setting the libraryTarget
to var
. This will still emit the webpack wrapper code, but it will evaluate your entry point and assign the exports of your entry point to a variable based on the value of library
.
module.exports = {
entry: './entry.js',
mode: 'production',
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var',
library: 'YourLibraryNameHere'
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.