Having a first go at webpack.
In my root directory I have my main.js entry point and am also checking for .js and .scss files
It does compile the main.js file.
Webpack cannot seem to find any other .scss or .js files. What have I done wrong.
Full config below:
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: './main.js',
output: {
path: path.resolve(__dirname, './dist3'),
filename: 'bundle5.js'
},
module: {
rules: [
{ test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader?presets[]=es2015",
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader'],
fallback: 'style-loader',
})
},
]
},
plugins: [
//new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('ross.css')
]
};
Webpack does not just include every file that is in your project, but instead starts from the entry point(s) and includes everything that is required in these files and their dependencies. If you want files to be included in your bundle you import them, even scss or other non-JavaScript files, and the loaders that match some rules will transform them to valid JavaScript. For example you can import an .scss file in JavaScript:
import './styles.scss';
You can also have multiple entry points that will add them with all their dependencies into the bundle. Take a look at the official docs for entry points: https://webpack.js.org/concepts/entry-points/
The loaders you define in module.rules just tell webpack how to process imports that match the regular expression you're using. For more information see: https://webpack.js.org/concepts/loaders/
Related
I encountered a "_typeof is not defined" error when I imported jstree.js with "rails/webpacker",i.e. Webpack in Rails6. This error seems to be caused by Babel. Babel defined _typeof function in front of source code of jstree.js and then replaced all typeof with _typeof . However, the _typeof function is regarded undefined.
I was told that it could be solved by setting exclude: /node_modules/ on babel-loader.
I checked default configuration of babel-loader in file config/webpack/environment.js
const { environment } = require('#rails/webpacker')
const babelLoader = environment.loaders.get('babel')
console.log(babelLoader);
result is :
test: /\.(js|jsx|mjs)?(\.erb)?$/,
include: [ '/home/demo/app_tree/app/javascript' ],
exclude: /node_modules/,
use: [ { loader: 'babel-loader', options: [Object] } ]
It seems that webpacker's default config file has excluded node_modules from babel-loader . Nothing could be done to fix it.
Finally I solved this error , thanks to guide here
https://github.com/rails/webpacker/blob/54c3ca9245e9ee330f8ca63b447c202290f7b624/docs/v4-upgrade.md#excluding-node_modules-from-being-transpiled-by-babel-loader
Effecitve method is to delete "NodeModule" by adding following lines in file config/webpack/environment.js
const { environment } = require('#rails/webpacker')
environment.loaders.delete('nodeModules')
I am still confused although error is fixed .
Why does "exclude: /node_modules/" attribute of babel-loader not work in this case? It looks exactly right according to official document of webpack.
How does rails/webpacker map all configurations to file webpack.config.js ?
Where can I review the file webpack.config.js which is eventually used by webpack?
Thank you !
I have created an app which uses Rails and a React front-end (rails new my-app --webpack=react)
I've worked with Rails and React separately before but never when integrated this way.
As the app is served on rails s, my understanding is that this is essentially working as a rails app which is rendering React components, so I believe be that the environment variables would be defined in config/application.yml rather than a .env, but I have tried both and can't get access to them in the React components
What I have tried
variables in .env and application.yml
dotenv-webpack
webpack DefinePlugin
adding my env files in config/webpack/environment.js
Prefixing with REACT_APP
Hardcoding the variable into the webpack config
I'm running the rails server as well as ./bin/webpack-dev-server, and also run "webpack --config webpack.config.js" before starting the servers.
My webpack.config.js
const Dotenv = require('dotenv-webpack');
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, '') + '/app/javascript/packs/index.jsx',
plugins: [
new Dotenv(),
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify('5fa3b9'),
BROWSER_SUPPORTS_HTML5: true,
TWO: '1+1',
'typeof window': JSON.stringify('object'),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.REACT_APP_LAST_FM_API_KEY': JSON.stringify('myApiKeyfs89fs08a0')
})
],
module: {
rules: [
{ test: /\.jsx$/, use: {loader:'babel-loader'} },
{ test: /\.js$/, use: {loader:'babel-loader'} }
]
},
node: {fs:"empty"},
output: {
publicPath: '/'
}
};
In the end, I didn't need to do any of the above things. I just needed the .env file and to add
const dotenv = require('dotenv')
dotenv.config()
to my config/webpack/development.js
I use Webpack 4 in a project where I only need to compile and bundle styles so far. There's no Javascript.
Here's the config I have:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
'css/bundle': path.resolve(__dirname, 'static/scss/index.scss'),
},
output: {
path: path.resolve(__dirname, 'static'),
},
module: {
rules: [
{
test: /\.s[ac]ss$/,
include: path.resolve(__dirname, 'static/scss'),
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin(),
],
};
The problem is that it outputs two files: bundle.css and bundle.js. Is there a way to configure Webpack so that it doesn't output the Javascript bundle? I tried to navigate the docs, tried a dozen different things, but it didn't really work.
One important note here is that if I remove the css-loader, bundling fails. So while css-loader is most likely responsible for outputting the bundle.js file, I'm not entirely sure how to avoid using it.
webpack-extraneous-file-cleanup-plugin has no effect with webpack 4.12.0.
I can suggest to remove bundle.js manually with on-build-webpack plugin:
var WebpackOnBuildPlugin = require('on-build-webpack');
// ...
plugins: [
// ...
new WebpackOnBuildPlugin(function () {
fs.unlinkSync(path.join('path/to/build', 'bundle.js'));
}),
],
March 2021:
In Webpack 5, on-build-webpack plugin did not work for me.
I found this:
Webpack Shell Plugin Next
The project I’m working on we’re using Webpack 5 as a build tool for a CSS pattern library. Therefore, we didn’t need the main.js in our dist.
Run npm i -D webpack-shell-plugin-next
Then in webpack.config.ts (just showing the pertinent parts):
import WebpackShellPluginNext from "webpack-shell-plugin-next";
module.exports = {
output: {
path: path.resolve(__dirname, "static/dist")
},
plugins: [
// Run commands before or after webpack 5 builds:
new WebpackShellPluginNext({
onBuildEnd: {
scripts: [
() => {
fs.unlinkSync(path.join(config.output.path, "main.js"));
}
]
}
})
]
};
export default config;
Unfortunately, this is just the way that webpack currently works. However, we are not alone in this problem! There's a plugin to cleanup any unwanted files:
install the plugin:
yarn add webpack-extraneous-file-cleanup-plugin -D
and then in your config:
const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');
plugins: [
new ExtraneousFileCleanupPlugin({
extensions: ['.js'],
minBytes: 1024,
paths: ['./static']
}),
]
I simply delete the unneeded output with rm in package.json:
"scripts": {
"build": "npm run clean && webpack -p && rm ./dist/unneeded.js"
},
The webpack-remove-empty-scripts plugin, compatible with webpack 5, cover the current issue. It remove unexpected empty js file.
I am migrating from gulp/jspm to webpack. Everything is seemingly going fine by our SASS. In gulp our task looks like so:
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var autoprefixer = require('autoprefixer');
var paths = require('../paths');
var flatten = require('gulp-flatten');
var postcss = require('gulp-postcss');
gulp.task('build-sass', () => {
return gulp.src(paths.sassSource)
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(postcss([autoprefixer()]))
.pipe(flatten())
.pipe(sourcemaps.write('/maps'))
.pipe(gulp.dest(paths.output + 'css'));
});
And thus works perfectly. This is my current webpack config for SASS:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: 'css-loader?sourceMap!postcss-loader!sass-loader?sourceMap',
}),
},
And in the plugins I have:
new ExtractTextPlugin({
filename: 'global.css',
allChunks: true,
}),
The problem is when I run webpack I get these SASS errors:
ERROR in ./~/css-loader?sourceMap!./~/postcss-loader!./~/sass-loader?sourceMap!./src/sass/base/_QB4-variables.scss
Module build failed:
$never-signed-in: $gray-light;
^
Undefined variable: "$gray-light".
in /Users/allen/work/TwentyTwenty.QualBoard.Web/src/sass/base/_QB4-variables.scss (line 31, column 19)
I am getting tons of those type of errors which I don't understand since the gulp sass tool never threw those errors before. I feel like some configuration is missing.
In my main.js file I was missing my sass include. Thus it was just compiling all that sass but with no particular order.
Tyring to use webpack to bundle my depenedencies to be used in karma spec files. But getting:
Module 'fuse' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Fuse is the name of ng-app.
this same setup works when I run on standard tests, but when I try to: beforeEach(module('fuse')); the app breaks with the above error.
Here is my Karma.conf:
// Karma configuration
var webpackConfig = require('./webpack.dev.config.js');
webpackConfig.entry = {};
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
reporters: ['progress'],
port: 9876,
colors: false,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS', 'Chrome'],
singleRun: false,
autoWatchBatchDelay: 300,
// ... normal karma configuration
files: [
'node_modules/jquery/dist/jquery.js',
'./node_modules/angular/angular.js',
'./node_modules/angular-mocks/angular-mocks.js',
// 'public/app/pages/main/**/*.spec.js',
'../../app.js',
'public/app/services/auth/auth_service.spec.js'
],
preprocessors: {
// add webpack as preprocessor
'../../app.js': ['webpack'],
},
webpack: webpackConfig,
webpackMiddleware: {
// webpack-dev-middleware configuration
// i. e.
noInfo: true
},
plugins: [
require("karma-webpack"),
require("karma-jasmine"),
require("karma-chrome-launcher"),
require("karma-phantomjs-launcher")
]
});
};
Any idea what is going on? I've tried so many things and am almost out of ideas, will keep trying to reorder the files being loaded.