How to exclude files from a webpack entry point - javascript

I am using the following webpack config to handle / load all of my sass files. One important item is that I am using additionalData to preappend my common styles. This is causing a conflict, however, because my entry for webpack is any and all sass files, which means that my commonStyles.scss is already getting loaded. When I run my app, I get the following error:
errorMessage:
SassError: This file is already being loaded.
╷
1 │ #import "src/styles/commonStyles.scss";
│ ^^^^^^^^^^^^^^^^^^^^^^^
╵
src/styles/sizes.scss 1:9 root stylesheet
How can I create an entry point that includes all sass files in my app except for / excluding commonStyles.scss (or better yet, any files in the /src/styles/ folder)? Thanks for the help!
webpack config:
'use strict';
const fs = require('fs');
const glob = require('glob');
const path = require('path');
const sassRegex = /\.(scss|sass)$/;
module.exports = {
mode: 'production',
bail: true,
devtool: false,
entry: glob.sync(`${path.resolve(fs.realpathSync(process.cwd()), 'src')}/**/*.{css,scss}`),
output: {
path: 'build',
},
module: {
rules: [
{
test: sassRegex,
exclude: /node_modules/,
use: [
{
loader: 'sass-loader',
options: {
sourceMap: true,
additionalData: `#import "src/styles/commonStyles.scss";`,
},
},
],
},
],
},
};

Instead of
/**/*.{css,scss} try /**/!{commonStyles}.{css,scss}
Alternatively:
entry: glob.sync(
`${path.resolve(fs.realpathSync(process.cwd()), 'src')}/**/*.{css,scss}`,
ignore: [
'**/src/styles/commonStyles.scss',
],
),

Related

How do I prevent webpack from throwing typescript errors for unused modules?

I have the following structure:
└── src
├── tsconfig.json
├── core
│ ├── [...].ts
└── ui
├── [...].tsx
└── tsconfig.json
In the frontend I import a small number of modules from the core. These modules, and any dependent modules, are compliant with both tsconfig files.
tsc and eslint pass with no errors and webpack builds the desired output file. So far so good.
However when webpack builds it throws loads of type errors for other backend modules.
How do I suppress these errors? I tried excluding src/core from babel-loader and including the required modules but I was still getting the same errors.
/// webpack.config.js
/* eslint-disable #typescript-eslint/no-var-requires */
const path = require('path');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/ui',
output: {
path: path.resolve(__dirname, './ui-dist'),
},
// Enable sourcemaps for debugging webpack's output.
devtool: 'source-map',
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
'#babel/preset-env',
{ targets: { browsers: 'last 2 versions' } }, // or whatever your project requires
],
'#babel/preset-typescript',
'#babel/preset-react',
],
plugins: [
// plugin-proposal-decorators is only needed if you're using experimental decorators
// in TypeScript
['#babel/plugin-proposal-decorators', { legacy: true }],
['#babel/plugin-transform-runtime', { legacy: true }],
['#babel/plugin-proposal-class-properties', { loose: true }],
'react-hot-loader/babel',
],
},
},
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader',
},
],
},
plugins: [
new ForkTsCheckerWebpackPlugin({
tsconfig: path.resolve(__dirname, './src/ui/tsconfig.json'),
eslint: true,
/** Options to supply to eslint https://eslint.org/docs/developer-guide/nodejs-api#cliengine */
// eslintOptions: EslintOptions;
}),
new HtmlWebpackPlugin({
title: 'development',
template: './src/ui/template.html',
}),
],
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
// externals: {
// react: 'React',
// 'react-dom': 'ReactDOM',
// },
devServer: {
contentBase: path.resolve(__dirname, './ui-dist'),
},
};
EDIT: I suppose I am referencing these modules throwing an error by using import type { x } from '../core/index.ts'. Perhaps I need to find a way for babel-loader to skip scanning type imports.
removing ForkTsCheckerWebpackPlugin did the trick. Type checking is done when calling tsc in any case.

How to get webpack minimizer to work when bundling css into js

I am trying to figure out webpack. I want to bundle a css and js file while also minimizing them at the same time. I am using optimize-css-assets-webpack-plugin and got it to work together with mini-css-extract-plugin. But, when bundling css into js with style-loader, the css is no longer minified. Does anyone have any ideas on what I can do to make this work?
Index js file:
import './styles.css';
// some js
Webpack config:
const path = require('path');
const OptimizeCss = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const bundle = {
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, './'),
},
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader'
],
},
],
},
optimization: {
minimizer: [
new OptimizeCss(),
new TerserPlugin()
]
},
mode: 'production',
watch: false
}
module.exports = bundle;
Edit: I am using webpack version 4.39.3

Webpack: vendor bundle not imported in main output

I'm struggling with what looks like a generic error from Webpack after trying to optimise my source code.
Assuming I have the following files in ./src:
├── main.js
├── moduleA.js
└── moduleB.js
main.js imports and uses ModuleA.
moduleA.js imports and uses ModuleB
ModuleA.js and ModuleB.js both import flatten-array from node_modules
My expectation is that if I try to optimise my bundle (see below) it will output two files:
1. index.js
2. vendors~main.index.js
Trying to execute the index.js output bundle results in:
/******/ modules[moduleId].call(module.exports, module,
module.exports, __webpack_require__);
^
TypeError: Cannot read property 'call' of undefined
Although the files are generated, index.js doesn't appear to import vendors~main.index.js. Yet it executes fine when removing the optimization (and vendors javascript)
Is this the correct assumption? How can I make it work like this?
While this is a bundle for Node, there are valid reasons that I'd like to export a vendors file.
Accompanying git repo to reproduce available here:
https://github.com/supasympa/webpack-vendors-issue
Files are:
main.js
const moduleA = require('./moduleA');
moduleA.log('log from main.js');
moduleA.js
const moduleB = require('./moduleB');
const flatten = require('array-flatten');
module.exports.log = function(msg){
moduleB.log('logging from moduleA.js');
console.log(`ModuleA logging: ${msg}`);
console.log(`flattened: ${flatten([[1,2,3],[4,5],[6,7]])}`)
};
moduleB.js
const flatten = require('array-flatten');
module.exports.log = function(msg){
console.log(`ModuleB logging: ${msg}`);
console.log(`flattened: ${flatten([[1,2,3],[4,5],[6,7]])}`)
};
webpack.config.js
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
module: {
rules: [{
include: [path.resolve(__dirname, 'src')],
loader: 'babel-loader',
options: {
plugins: ['syntax-dynamic-import'],
presets: [['env', {
'modules': 'commonjs'
}]]
},
test: /\.js$/
}]
},
entry: './src/main',
target: 'node',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
priority: -10,
test: /[\\/]node_modules[\\/]/,
enforce: true
},
},
// concatenateModules: false,
chunks: 'all',
minChunks: 1,
minSize: 0,
name: true
}
},
plugins: [
new CleanWebpackPlugin(['dist']),
]
};
It turns out that this is not yet implemented outside of the browser, in Webpack.
https://github.com/webpack/webpack/issues/8330
https://github.com/webpack/webpack/issues/8161
https://github.com/webpack/webpack/issues/8156
Defining, chunks: 'all', you're explicitly taking all initial entries and async imports (by default it only on-demand async chunks) and specifying the bundler to create a new vendor chunk/file out of that.
So the behavior is as expected. The idea is to remove the common dependencies from entry files so they can be shared and the page has to load less vendors/common code overall.
One way to explicitly control what the entry files include is this pattern: https://github.com/webpack/webpack/tree/master/examples/two-explicit-vendor-chunks

Getting Error: Module parse failed: ... unexpected character '#'

I am using webpack for the first time and want to use some css with my react/redux application. I followed a guide, but still seem to be having problems. I am getting the above error as you can see.
folder structure looks like this:
.git
-node_modules
-public
-bundle.js
-index.html
-src
-actions
-components
-reducers
app.js
-style
-style.css
.babelrc
.gitingore
package-lock.json
package.json
README.md
server.js
webpack.config.js
This is the exact error:
Uncaught Error: Module parse failed: C:\Users\Amazo\projects\reduxApp\style\style.css Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #row1 {
| margin-top: 15px;
| }
I will post my webpack config file below:
var path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude:/node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['.js','.jsx']
},
plugins: [
new HTMLWebpackPlugin({
template: 'public/index.html';
}),
new ExtractTextPlugin('style.css')
]
};
Add .css to your resolve
resolve: {
extensions: ['.js','.jsx', '.css']
},
Otherwise, webpack won't be able to process it correctly

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'] })
];
},
}

Categories

Resources