From this blogpost example https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript, I tried to get scss variables in my js code and I did not manage to do it.
index.js file
import variables from './variables.scss';
console.log(variables);
variables.scss file
$myvar: 100;
:export {
myvar: $myvar;
}
webpack.config.js file
module.exports = {
mode: 'development',
module: {
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: 'css-loader'
}, {
loader: 'sass-loader'
}]
}]
}
};
dependencies in package.json file
"dependencies": {
"css-loader": "^5.0.2",
"lodash": "^4.17.20",
"postcss-loader": "^5.0.0",
"sass": "^1.32.6",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0"
}
Compilation : npx webpackOutput :
asset main.js 17.2 KiB [compared for emit] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 9.23 KiB
modules by path ./src/ 1020 bytes
./src/index.js 324 bytes [built] [code generated]
./src/variables.scss 371 bytes [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./src/variables.scss 325 bytes [built] [code generated]
modules by path ./node_modules/ 8.23 KiB
./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built] [code generated]
./node_modules/css-loader/dist/runtime/api.js 1.57 KiB [built] [code generated]
webpack 5.21.2 compiled successfully in 503 ms
In the web console, the object variables is empty and of course, I could not use variables.myvar.
Is there a configuration problem in webpack.config.js ? I tried to simplify it as much as possible. All node_modules are up to date and npm version is 6.14.9.
Thanks for help.
I wasn't aware of it but maybe this only works for "css modules". I never tried it without having css-loader configured to be module based. (you can see in my config in this answer that modules are activated)
Please try the following: rename your variables.scss into variables.module.scss
Because by default the css-loader will treat your files as modules or not as modules based on the filename (https://webpack.js.org/loaders/css-loader/#modules).
Related
I'm trying to create a boilerplate with Webpack 5 and React to understand the details all of the elements. And it seems like everything works properly except the updating bundle.js in memory.
When I run the 'webpack serve' command the server starts, then I modify script, page is reloaded but there are no changes.
I have next statement in config files
package.json:
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack serve",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#babel/core": "^7.16.0",
"#babel/preset-env": "^7.16.4",
"#babel/preset-react": "^7.16.0",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"dotenv-webpack": "^7.0.3",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.64.1",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.5.0"
}
}
webpack.config.js:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const DotenvWebpackPlugin = require('dotenv-webpack');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.bundle.js',
},
devServer: {
static: {
directory: path.join(__dirname, 'src'),
},
port: 8080,
open: true,
hot: true,
liveReload: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
devtool: 'inline-source-map',
plugins: [
new HtmlWebpackPlugin({ template: './src/index.html' }),
new DotenvWebpackPlugin({
path: '.env'
})
],
stats: {
errorDetails: true,
},
}
Logs:
<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:8080/
<i> [webpack-dev-server] On Your Network (IPv4): http://192.168.0.106:8080/
<i> [webpack-dev-server] Content not from webpack is served from 'D:\Projects\boilerplates\react-app\src' directory
<i> [webpack-dev-middleware] wait until bundle finished: /
[BABEL] Note: The code generator has deoptimised the styling of D:\Projects\boilerplates\react-app\node_modules\react-dom\cjs\react-dom.development.js as it exceeds the max of 500KB.
asset index.bundle.js 4.06 MiB [emitted] (name: main)
asset index.html 287 bytes [emitted]
runtime modules 27.1 KiB 13 modules
modules by path ./node_modules/ 1.06 MiB 45 modules
modules by path ./src/ 3.29 KiB
modules by path ./src/*.js 477 bytes
./src/index.js 200 bytes [built] [code generated]
./src/App.js 277 bytes [built] [code generated]
modules by path ./src/*.css 2.83 KiB
./src/app.css 2.24 KiB [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./src/app.css 601 bytes [built] [code generated]
webpack 5.64.1 compiled successfully in 3107 ms
assets by path *.js 4.06 MiB
asset index.bundle.js 4.06 MiB [emitted] (name: main)
asset main.c161a0c51f50fe5a9631.hot-update.js 676 bytes [emitted] [immutable] [hmr] (name: main)
asset index.html 287 bytes [emitted]
asset main.c161a0c51f50fe5a9631.hot-update.json 28 bytes [emitted] [immutable] [hmr]
Entrypoint main 4.06 MiB = index.bundle.js 4.06 MiB main.c161a0c51f50fe5a9631.hot-update.js 676 bytes
cached modules 1.07 MiB [cached] 48 modules
runtime modules 27.1 KiB 13 modules
./src/App.js 277 bytes [built]
webpack 5.64.1 compiled successfully in 118 ms
assets by status 4.06 MiB [cached] 1 asset
asset index.html 287 bytes [emitted]
cached modules 1.07 MiB (javascript) 27.1 KiB (runtime) [cached] 62 modules
webpack 5.64.1 compiled successfully in 15 ms
<i> [webpack-dev-middleware] wait until bundle finished: /
assets by status 4.06 MiB [cached] 1 asset
asset index.html 287 bytes [emitted]
cached modules 1.07 MiB (javascript) 27.1 KiB (runtime) [cached] 62 modules
webpack 5.64.1 compiled successfully in 16 ms
You can check the boilerplate here in repo
So, page is reloaded successfully but there are no changes. What the problem can be there?
UPDATE 1:
I'm updating jsx inside of this script for anything else - src/app.js
import React from "react";
function App() {
return (<div>
<h2>Welcome to React App</h2>
<h3>Date : {new Date().toDateString()}</h3>
</div>)
}
export default App
But the changes are visible only after restarting webpack dev server.
To reproduce the problem you can easily clone the repo and run this script in react-app directory:
npm i
npm start
I found the problem.
index.js had:
import App from "./App"
but correct one is:
import App from "./app"
Strange thing. It's like there should be an error instead of silence.
I just need to minify and bundle all my js files into one file. So prepared a simple configuration as;
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
resolve: {
extensions: ['.js']
},
entry: [
'./src/main/resources/static/js/app/context.js',
'./src/main/resources/static/js/app/pagemanager.js'
],
plugins: [
new CleanWebpackPlugin()
],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
}
};
but if I execute webpack --mode production it produces 0 bytes and bundle.js is empty
asset bundle.js 0 bytes [emitted] [minimized] (name: main)
./src/main/resources/static/js/app/context.js 9.74 KiB [built] [code generated]
./src/main/resources/static/js/app/pagemanager.js 27.9 KiB [built] [code generated]
webpack 5.20.2 compiled successfully in 299 ms
but with webpack --mode development it creates a file that contains js code.
What may be the reason leading to this? Thank you.
I think that if your file don't have any code to execute, such as
// just define a var
const foo = 1;
// or just a string
"console.log('something');"
and the webpack mode is "production"(if you don't set it, the default value is this),the result will be empty, asset main.js 0 bytes.
The solution is changing the code to this.
console.log('something');
Answering my question for those who is facing the same problem,
There should be "export" syntax, that refers what you export from these js files to solve this problem.
I am working on a project where I am using several sass files and I am calling them into one single file, the problem is that when I try to apply the styles they don't show up.
sass files. Now this is how i configured my webpack.config.js file
const path = require("path");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
assetModuleFilename: "images/[hash][ext][query]",
},
devtool: "inline-source-map",
devServer: {
contentBase: "./dist",
},
module: {
rules: [
{
test: /\.(s[ac]|c)ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
generator: {
filename: "static/[hash][ext][query]",
},
},
],
},
};
and this is the error i get
> restaurant#1.0.0 start /home/cvilla714/javascript/restaurant-page
> webpack serve --open
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from ./dist
ℹ 「wdm」: wait until bundle finished: /
✖ 「wdm」: asset main.js 943 KiB [emitted] (name: main)
runtime modules 1.25 KiB 6 modules
modules by path ./node_modules/ 345 KiB 26 modules
modules by path ./sass/*.scss 2.4 KiB
./sass/tabs.scss 366 bytes [built] [code generated]
./sass/main.scss 366 bytes [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./sass/tabs.scss 1.64 KiB [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./sass/main.scss 39 bytes [built] [code generated] [1 error]
modules by path ./src/*.js 4.48 KiB
./src/index.js 201 bytes [built] [code generated]
./src/tabs.js 2.42 KiB [built] [code generated]
./src/nav.js 1.86 KiB [built] [code generated]
ERROR in ./sass/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./sass/main.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: expected "{".
╷
7 │ $font-dancingScript: "Dancing Script", cursive;
│ ^
╵
sass/_layout.scss 7:47 #import
sass/main.scss 2:9 root stylesheet
# ./sass/main.scss 2:12-127 9:17-24 13:15-29
# ./src/nav.js 4:0-27
# ./src/index.js 3:0-31
webpack 5.18.0 compiled with 1 error in 2816 ms
ℹ 「wdm」: Failed to compile.
this is how I am importing the style to the project
import "../sass/main.scss";
I can't apply my styles to the project, I have been trying all day to fix this issue with no success, I would really appreciate if someone can please point me in the right direction.
Your Webpack config is correct. Error in your
$font-dancingScript: "Dancing Script", cursive;
adding ' must solve your problem;
$font-dancingScript: ' "Dancing Script", cursive ';
Config:
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.s[ac]ss$/i,
use: ["style-loader","css-loader","sass-loader"],
}
tl;dr: Webpack won't compile and I'm not sure why when everything looks syntactically correct, and also I don't fully understand what this error is implying.
Trying to use webpack. Full disclosure: really new to this (js/front end in general). I finally resolved the other errors I was getting (mostly just pointing to wrong filepaths or syntax errors). I followed a youtube video to get this set up , which in hindsight might not have been the best idea, but I needed to begin somewhere and watching is easier than reading. Anyway so I followed that and got things moving. Installed everything with npm (see package.json below) and created the src/dist and so forth. I am not using React/Angular/Vue etc, just regular plain old vanilla javascript. And I'm on Linux, if that makes any bit of difference (I'd imagine not).
Then I was met with this error:
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /home/alan/dev/privateFolder/shrektime
ℹ 「wdm」: wait until bundle finished: /
✖ 「wdm」: Hash: 91bf4b6307b254c69adc
Version: webpack 4.44.1
Time: 1110ms
Built at: 04/09/2020 04:20:38
Asset Size Chunks Chunk Names
.dist/index.html 1.39 KiB [emitted]
55e664c36a02d03a083764a7c577f012.png 17.2 KiB [emitted] [immutable]
bundle.js 374 KiB main [emitted] main
Entrypoint main = bundle.js
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./src/main.js 40 bytes {main} [built]
[./node_modules/strip-ansi/index.js] 161 bytes {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.91 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./src/js/components/Calendar.js] 1.18 KiB {main} [built]
[./src/js/components/Input.js] 171 bytes {main} [built]
[./src/js/components/Results.js] 603 bytes {main} [built]
[./src/js/handlers/base.js] 356 bytes {main} [built]
[./src/main.js] 2.7 KiB {main} [built]
+ 23 hidden modules
ERROR in Error: /home/alan/dev/privateFolder/shrektime/node_modules/style-loader/dist/runtime/injectStylesIntoSty leTag.js?:93
var style = document.createElement('style');
^
ReferenceError: document is not defined
- injectStylesIntoStyleTag.js?:93 insertStyleElement
[.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:93:15
- injectStylesIntoStyleTag.js?:208 addStyle
[.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:208:13
- injectStylesIntoStyleTag.js?:81 modulesToDom
[.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:81:18
- injectStylesIntoStyleTag.js?:239 module.exports
[.]/[style-loader]/dist/runtime/injectStylesIntoStyleTag.js?:239:25
- style.css?:15 eval
/home/alan/dev/privateFolder/shrektime/src/style.css?:15:14
- index.html:240 Object../src/style.css
/home/alan/dev/privateFolder/shrektime/src/index.html:240:1
- index.html:21 __webpack_require__
/home/alan/dev/privateFolder/shrektime/src/index.html:21:30
- loader.js:3 eval
[index.html?.]/[html-webpack-plugin]/lib/loader.js:3:34
- index.html:133 Object../node_modules/html-webpack-plugin/lib/loader.js!./src /index.html
/home/alan/dev/privateFolder/shrektime/src/index.html:133:1
- index.html:21 __webpack_require__
/home/alan/dev/privateFolder/shrektime/src/index.html:21:30
Child HtmlWebpackCompiler:
Asset Size Chunks Chunk Names
55e664c36a02d03a083764a7c577f012.png 17.2 KiB [emitted] [immutable]
+ 1 hidden asset
Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
[./node_modules/css-loader/dist/cjs.js!./src/style.css] 5.29 KiB {HtmlWebpackPlugin_0} [built]
[./node_modules/css-loader/dist/runtime/api.js] 2.46 KiB {HtmlWebpackPlugin_0} [built]
[./node_modules/html-loader/dist/runtime/getUrl.js] 548 bytes {HtmlWebpackPlugin_0} [built]
[./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 4.34 KiB {HtmlWebpackPlugin_0} [built]
[./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js] 6.64 KiB {HtmlWebpackPlugin_0} [built]
[./src/img/icons8-shrek-256.png] 80 bytes {HtmlWebpackPlugin_0} [built]
[./src/js/components/Calendar.js] 1.18 KiB {HtmlWebpackPlugin_0} [built]
[./src/js/components/Input.js] 171 bytes {HtmlWebpackPlugin_0} [built]
[./src/js/components/Results.js] 603 bytes {HtmlWebpackPlugin_0} [built]
[./src/js/handlers/base.js] 356 bytes {HtmlWebpackPlugin_0} [built]
[./src/js/handlers/dateHandler.js] 1.97 KiB {HtmlWebpackPlugin_0} [built]
[./src/main.js] 2.7 KiB {HtmlWebpackPlugin_0} [built]
[./src/style.css] 519 bytes {HtmlWebpackPlugin_0} [built]
ℹ 「wdm」: Failed to compile.
here is my package.json
{
"name": "shrektime",
"version": "1.0.0",
"description": "A stupid idea gone too far",
"main": "main.js",
"type": "module",
"dependencies": {
"fractional": "^1.0.0",
"lodash": "^4.17.20",
"moment": "^2.27.0"
},
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/preset-env": "^7.11.5",
"babel-loader": "^8.1.0",
"css-loader": "^4.2.2",
"file-loader": "^6.1.0",
"html-loader": "^1.3.0",
"html-webpack-plugin": "^4.4.1",
"mini-css-extract-plugin": "^0.11.0",
"node-sass": "^4.14.1",
"sass-loader": "^10.0.2",
"style-loader": "^1.2.1",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"scripts": {
"compile:sass": "node-sass src/sass/main.scss src/style.css -w",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode-development --open"
},
"author": "Alan Nardo",
"license": "ISC"
}
in my main.js folder I have the CSS and Sass imported as such:
import sass from './sass/main.scss';
import css from './style.css';
and finally my webpack.config.js file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
module.exports = {
entry: "./src/main.js",
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: { loader: "babel-loader" }
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{ loader: "file-loader" }
]
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
],
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: ".dist/index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
This is an image of my folder structure:
I just had, and solved this issue, without finding an answer on stackoverflow.
So here how I caused this problem:
In webpack, in your loader section, if you leave out the 'test' part of your rule,
you may trigger this error.
The issue is, that webpack will invoke your loader
on the wrong kinds of files, and give errors like this.
..
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader', exclude: /node_modules/
},
]
}
..
(I'm aware the above question contains tests, but my reputation is too low to comment, and I believe understanding the underlying causes of the error is relevant to figuring out how to solve them. I don't like unexplained 'I did thing and now it works!! kinds of answers.)
So I'm not sure if anyone else will have quite the same error, but just in case, there's nothing worse than searching forums and finding the exact same error and nobody leaving an answer.
I got help from a friendly redditor (shoutout r/learnjavascript) and it was basically just a few syntax errors here and there and me not understanding how things work.
under the HtmlWebpackPlugin I had to change the filename from .dist/index.html to index.html and had to add in the following code in the module.exports of webpack.config.js for the webpack-dev-server to run:
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
which is pulled right from the docs page https://webpack.js.org/configuration/dev-server/#devserver. Presumably you can choose any port number you fancy.
Additionally, I had to change how I imported one of my js files as it is a class (and tbh I should probably change that but I'll cross that bridge when I get to it). It's called Calendar.js so instead of doing import * as Calendar from './Calendar' I had to use import Calendar from './Calendar'.
Finally, in my src/index.html I left in the style and script tags for the css and main.js respectively, so I had to remove those.
Suppose you have a project below:
package.json
{
"name": "webpack-test-repo",
"main": "index.js",
"dependencies": {
"define-properties": "^1.1.3"
},
"devDependencies": {
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
}
}
index.js
// dynamically load the 'define-properties' module.
import('define-properties');
webpack.config.js
module.exports = {
mode: 'production',
entry: './index.js',
output: {
chunkFilename: '[name].js',
},
optimization: {
splitChunks: {
minSize: 0, // <- just to demonstrate the situation with small packages
cacheGroups: {
defineProperties: {
test: /node_modules\/define-properties\//,
name: 'define-properties',
},
},
},
},
};
Note that the imported module define-properties has a single dependency object-keys.
I configured splitChunks in webpack.config.js so that contents of define-properties are split into define-properties.js.
The result of running webpack is as follows:
$ npx webpack
Hash: 7d9500fb0e6bfd1e32d1
Version: webpack 4.20.2
Time: 127ms
Built at: 2018-10-08 03:25:47
Asset Size Chunks Chunk Names
main.js 2.05 KiB 0 [emitted] main
define-properties.js 754 bytes 1 [emitted] define-properties
2.js 2.08 KiB 2 [emitted]
Entrypoint main = main.js
[0] ./index.js 81 bytes {0} [built]
+ 3 hidden modules
Here we get three output files: main.js for the content of index.js, define-properties.js for the define-properties module, and 2.js for the object-keys module.
Question:
I want the chunk for object-keys to be merged into define-properties because it is only used by define-properties.
In other words, I want to pack define-properties and its dependencies into one named chunk by only specifying the parent module.
Although test: /node_modules\/(?:define-properties|object-keys)\// works for this example, I don't want to list all (potentially many) dependencies of define-properties.
How do I configure webpack to achieve it?