Compiling with webpack into single file - javascript

So I have the following webpack.config.js file:
const path = require('path');
const JS_DIR = path.resolve(__dirname, '/js');
const BUILD_DIR = path.resolve(__dirname, 'js');
const entry = {
main: JS_DIR + '/main/main.js',
all: JS_DIR + '/all.js',
};
const output = {
path: BUILD_DIR,
filename: 'js/main/[name].js'
};
const rules = [
{
test: /\.js$/,
include: [ JS_DIR ],
exclude: /node_modules/,
// Loaders enable us to bundle the static assets.
use: 'babel-loader', // Allows for transpiling JS files using babel & webpack.
}
];
module.exports = () => ({
entry: entry,
output: output,
devtool: false, // Don't output any .map source files, otherwise 'source-map'.
module: {
rules: rules,
}
});
Currently, when I run npm run prod I get the following build:
It builds the additional /js directory inside the /js directory and then it has main/all.js and main/main.js. The all.js inside there is empty, but the main.js is the compiled stuff.
What I'm trying to achieve:
Instead of building the /js directory inside /js, how can I make the contents of js/main/main.js output to just the all.js in the main js directory? So basically like this:
All help would be appreciated!

Related

Compiling a typescript project with webpack

I have a question for you - how is it possible to implement multi-file compilation while preserving the tree of folders and documents, while not writing each file into entry in this way
entry: {
index:'./src/index.ts',
'bot/main':'./src/bot/main.ts'
}
But at the same time, the files had their names and their position, as before compilation in js, only instead of the src folder, they were in the dist folder?
My current config webpack.config.js
const path = require('path')
const nodeExternals = require('webpack-node-externals')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
module.exports = {
context: __dirname,
entry: {
index:'./src/index.ts',
'bot/main':'./src/bot/main.ts'
},
externals: [nodeExternals()],
module: {
rules: [
{
exclude: /node_modules/,
test: /.ts$/,
use: {
loader: 'ts-loader'
}
}
]
},
node: {
__dirname: false
},
resolve: {
extensions: ['.ts', '.js'],
plugins: [
new TsconfigPathsPlugin({
baseUrl: './src'
})
]
},
output: {
filename: '[name]js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/'
},
target: 'node'
}
And when building in production mode, all this was compiled into one file, taking into account all URLs, imports, etc.
Is it even possible?
Webpack itself won't do that for you. You will need to write litter helper function to achieve this. The basic idea is to crawl the directory, find all the files and then provide them to Webpack:
const path = require('path');
const glob = require('glob');
const extension = 'ts';
// Recursively find all the `.ts` files inside src folder.
const matchedFiles = glob.sync(`./src/**/*.${extension}`, {
nodir: true
});
const entry = {};
matchedFiles.forEach((file) => {
const SRC_FOLDER = path.join(__dirname, 'src');
const ABS_PATH = path.join(__dirname, file);
// Generates relative file paths like `src/test/file.ts`
const relativeFile = path.relative(SRC_FOLDER, ABS_PATH);
// fileKey is relative filename without extension.
// E.g. `src/test/file.ts` becomes `src/test/file`
const fileKey = path.join(path.dirname(relativeFile), path.basename(relativeFile, extension));
entry[fileKey] = relativeFile;
});
module.exports = {
context: __dirname,
// Use the entry object generated above.
entry,
// ... rest of the configuration
};

Webpack with requirejs/AMD

I'm working on a new module for an existing project that still uses requireJS for module loading. I'm trying to use new technologies for my new module like webpack (which allows me to use es6 loaders using es6 imports). It seems like webpack can't reconcile with requireJS syntax. It will say things like: "Module not found: Error: Can't resolve in ".
Problem: Webpack won't bundle files with requireJS/AMD syntax in them.
Question: Is there any way to make webpack play nice with requireJS?
My final output must be in AMD format in order for the project to properly load it. Thanks.
I had the same question and I managed to achieve it. Below is the same webpack.config.js file.
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
let basePath = path.join(__dirname, '/');
let config = {
// Entry, file to be bundled
entry: {
'main': basePath + '/src/main.js',
},
devtool: 'source-map',
output: {
// Output directory
path: basePath + '/dist/',
library: '[name]',
// [hash:6] with add a SHA based on file changes if the env is build
filename: env === EnvEnum.BUILD ? '[name]-[hash:6].min.js' : '[name].min.js',
libraryTarget: 'amd',
umdNamedDefine: true
},
module: {
rules: [{
test: /(\.js)$/,
exclude: /(node_modules|bower_components)/,
use: {
// babel-loader to convert ES6 code to ES5 + amdCleaning requirejs code into simple JS code, taking care of modules to load as desired
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: []
}
}
}, { test: /jQuery/, loader: 'expose-loader?$' },
{ test: /application/, loader: 'expose-loader?application' },
{ test: /base64/, loader: 'exports-loader?Base64' }
]
},
resolve: {
alias: {
'jQuery': 'bower_components/jquery/dist/jquery.min',
'application': 'main',
'base64': 'vendor/base64'
},
modules: [
// Files path which will be referenced while bundling
'src/**/*.js',
'src/bower_components',
path.resolve('./src')
],
extensions: ['.js'] // File types
},
plugins: [
]
};
module.exports = config;

jshint and sass/scss not working with Webpack 2.2

/Website
---/Scripts/*.js
---/sass/*.scss
---/dist/*.css
I want to do 2 things :
JShint the .js files
Compile the scss file and move them to dist folder
I tried this configuration, but it does't seem to work.
var webpack = require('webpack'),
path = require("path"),
glob = require("glob"),
jshint = require('jshint-loader'),
ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: glob.sync("./Scripts/**/*.js"),
output: {
path: "./Scripts/",
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "jshint-loader"
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css!sass')
}
]
},
resolve: {
extensions: [".js", ".css", ".sass", "scss"]
},
plugins: [
new ExtractTextPlugin('./dist/[name].css')
]
}
When I run webpack, the .js files are bundled into a main.js file and errors are emitted.
What am I missing to be able to JSHint the .js files
Is it possible to tell webpack to not bundle the files and just execute the JSHint
Why Im not getting the css files

Webpack error when importing CSS vendor library into index.js

I am moving existing javascript vendor libraries into a webpack setup, where possible using npm to install an npm module and deleting the old script tag on the individual page as bundle.js and bundle.css include it
In index.js, I have the following
import 'materialize-css/dist/css/materialize.min.css';
However, when webpack is run, it errors with the following
Module parse failed: .......Unexpected character ''
You may need an appropriate loader to handle this file type.
So, for some reason, webpack is looking at the entire materialize folder, rather than just the single minified css file, and is then error when it comes across materialize/fonts directory.
I am unclear why this is happening, and what to do to stop it. Any advice would be greatly appreciated.
My webpack config is below
const webpack = require('webpack');
const path = require('path');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var postcssImport = require('postcss-import');
module.exports = {
context: __dirname + '/frontend',
devtool: 'source-map',
entry: "./index.js",
output: {
filename: 'bundle.js',
path: path.join(__dirname, './static')
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', '!css-loader?sourceMap&importLoaders=1!postcss-loader')
}
]
},
plugins: [
new ExtractTextPlugin("si-styles.css")
],
postcss: function(webpack) {
return [
postcssImport({ addDependencyTo: webpack }), // Must be first item in list
precss,
autoprefixer({ browsers: ['last 2 versions'] })
];
},
}

How can I bundle all of my .scss files using my webpack.config.js file?

I'm trying to set up my webpack.config.js file to bundle my sass together. I have a file src/sass/index.scss that defines variables used elsewhere in the project. For example, my src/components/css/button.scss file uses the $my-special-green variable defined in the other file.
Is there way I can set up my webpack.config.js file to take my /src directory, find all of the .scss files recursively, and just bundle them into one bundle.css file? Ideally, I would like it all to happen in the webpack.config.js file.
I am able to require the individual .scss file in my entry.js file and that works, but I would like to avoid that if possible. Also, I understand that I could just import one .scss file into another, but I would also like to avoid that if possible.
if I do require the .scss file(s) in my entry.js file, they do get put in the public/bundle.css file that I am creating using ExtractTextPlugin, but I wonder if there is a way to have that happen based just off of this webpack.config.js file.
I thought that using
sassLoader: {
includePaths: [path.resolve(path.join(__dirname, "src"))]
}
might be the solution, but that doesn't really change anything in my case. I suppose that it really just ensures those paths are included when looking for the .scss files when requiring them in the javascript files?
my current webpack.config.js file looks like...
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var SRC_PATH = path.join(__dirname, 'src');
var BUILD_PATH = path.join(__dirname, 'dist');
var HTML_OPTS = {
filename: 'index.html',
title: 'My Page Title',
inject: true,
minify: { collapseWhitespace: true, },
templateContent: "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1'>" +
"<meta charset='utf-8'/>" +
"<title>{%= o.htmlWebpackPlugin.options.title %}</title>" +
"</head>" +
"<body>" +
"</body>" +
"</html>"
};
module.exports = {
context: SRC_PATH,
entry: [path.join(SRC_PATH, 'entry.js')],
resolve: {
root: SRC_PATH,
extensions: ['', '.js', '.jsx']
},
output: {
path: BUILD_PATH,
filename: 'index.js'
},
plugins: [
new HtmlWebpackPlugin(HTML_OPTS),
new ExtractTextPlugin('public/bundle.css', {
allChunks: true
})
],
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style', 'css!sass')
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query:
{
presets:['react']
}
}
]
},
sassLoader: {
includePaths: [path.resolve(path.join(__dirname, "src"))]
}
};

Categories

Resources