I'm trying to use bootstrap through webpack and have installed it using npm. I want to use it in my react project so I've done the below settings but I keep getting the below error:
main.js
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css'
const Main = () => (
<div className="container">yo</div>
)
Webpack config
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./client/pokeapp'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
},
// CSS
{
test: /\.css$/,
include: path.join(__dirname, 'client'),
loader: 'style-loader!css-loader'
},
{ test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'url'}
]
}
};
Console Error
Module parse failed: /Users/jlei/Desktop/pokeapp/node_modules/bootstrap/dist/css/bootstrap.css Unexpected token (7:5)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (7:5)
at Parser.pp$4.raise (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp.semicolon (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:581:61)
at Parser.pp$1.parseExpressionStatement (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:966:10)
at Parser.pp$1.parseStatement (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:730:24)
at Parser.pp$1.parseTopLevel (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:638:25)
at Parser.parse (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:516:17)
at Object.parse (/Users/jlei/Desktop/pokeapp/node_modules/acorn/dist/acorn.js:3098:39)
at Parser.parse (/Users/jlei/Desktop/pokeapp/node_modules/webpack/lib/Parser.js:902:15)
at DependenciesBlock.<anonymous> (/Users/jlei/Desktop/pokeapp/node_modules/webpack/lib/NormalModule.js:104:16)
# ./client/components/Main.js 27:0-43
What's the unexpected token? Is that due to my loader not working?
I tested your code and there is nothing wrong with the loader However this line include: path.join(__dirname, 'client') is causing the issue if you remove it you can see bootstrap bundling just fine with webpack.
For getting more from webpack you may want to get a separate css file then you can use ExtractTextPlugin to achieve it.
How it work ?
Installation
npm i extract-text-webpack-plugin
Configure it in webpack
{test: /\.css$/, loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader' })}
and add it in plugin
new ExtractTextPlugin('yourStyle.css')
Now you should have a separate css file in browser instead of every css in style tag
How does it work
It moves every require("style.css") in entry chunks into a separate css output file. So your styles are no longer inlined into the javascript, but separate in a css bundle file (styles.css). If your total stylesheet volume is big, it will be faster because the stylesheet bundle is loaded in parallel to the javascript bundle.
Hope it help you.
you don't have to include bootstrap as an npm module. You can download or use CDN to include bootstrap on your html template. You can then apply it on your component by using 'className' attribute instead of 'class'. Try it.
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));
and in your html file:
<link rel="stylesheet" href="/css/bootstrap.min.css">
This method is the same as downloading the bootstrap files to improve latency.
Related
I have very basic webpack + mini-css-extract-plugin project (you can found it here).
Here is webpack.config.js:
const path = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
resolve: {
modules: [path.resolve(process.cwd(), 'node_modules')]
},
module: {
rules: [
// file loader allows to copy file to the build folder and form proper url
// usually images are used from css files, see css loader below
{
test: /\.png$/,
exclude: /node_modules/,
use: [
{
loader: 'file-loader',
options: {
name: "_assets/[name].[ext]"
}
}
]
},
// css files are processed to copy any dependent resources like images
// then they copied to the build folder and inserted via link tag
{
test: /\.css$/i,
sideEffects: true,
exclude: /node_modules/,
// for tests we use simplified raw-loader for css files
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// public path has changed so url(...) inside css files use relative pathes
// like: url(../_assets/image.png) instead of absolute urls
publicPath: '../',
}
},
'css-loader'
]
}
]
},
plugins: [
// plugin helps to properly process css files which are imported from the source code
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '_assets/[name].css',
chunkFilename: '_assets/[id].css'
})
],
entry: {
'test': "./src/test"
},
output: {
path: path.resolve(process.cwd(), `public`),
publicPath: '',
filename: '[name].js',
chunkFilename: '_chunks/chunk.[name].js'
}
};
main entry file test.js:
import './css/testCss.css';
console.log('Loaded');
When i run webpack build i got the following output structure:
/
|-test.js
|-_assets/
| |-test.css
When i include this js bundle into html i would expect that test.js bundle will load test.css file dynamically but this is not the case - js bundle works ok, but css file is not loaded at all.
It is only loaded when i modify source of the test.js like so:
import('./css/testCss.css'); // <--------- NOTE: dynamic import here
console.log('Loaded');
in this case after webpack build i got the following output:
/
|-test.js
|-_assets/
| |-0.css
|-_chunks/
| |-chunk.0.js
and when i load this js bundle in html - it loads both chink.0.js and 0.css
MAIN QUESTION: Is dynamic import the only correct way to include css into my js files via mini-css-extract-plugin?
Because in documentation they say yo use normal static import like import "./test.css"
my environement info:
node version: v14.12.0
webpack version: 4.44.1 (also tested on 5.2.0)
mini-css-extract-plugin version 1.1.2
I want to dig into modern frontend development using Webpack 2 and Materialize. Because I might customize the style, I want to #import the Materialize SASS file into my own SASS file, so I can overwrite stuff. However, if I do that, Webpack 2 can't compile my SASS file anymore because it doesn't find the Materialize fonts.
This is my current webpack.config.js, copypasted from all over the internet:
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: "style.css",
disable: process.env.NODE_ENV === "development"
});
module.exports = {
entry: './src/js/index.js',
output: {
path: __dirname + '/public/dist',
filename: 'app.js'
},
module: {
rules: [
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}, {
loader: "resolve-url-loader"
}],
// use style-loader in development
fallback: "style-loader"
})
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=80000&mimetype=application/font-woff'
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
}
]
},
plugins: [
extractSass
]
};
I installed materialize-css via npm. If I put the following in my src/js/index.js file, the compilation works fine:
require('materialize-css/sass/materialize.scss');
I get the desired outputs in my public/dist directory (app.js, style.css and the font files that Materialize provides). But as I said, I want to import Materialize to my own SASS file, which looks something like this (src/scss/main.scss):
#import "~materialize-css/sass/materialize";
// ... overwrite some stuff here ...
Because of to the ~ in front of the filepath, the loader looks for the file in the node_modules directory, thus the materialize.scss file can be imported successfully.
I then have two possibilities to include my SASS file in my Webpack bundle: either change the require() call in my index.js to import that file instead of the materialize.scss file or change the entry key in my webpack.config.js to
entry: [
'./src/js/index.js',
'./src/scss/main.scss'
],
Either way, the compilation fails because Webpack cannot find the font files. This is one of the many errors that occur
ERROR in ./~/css-loader!./~/sass-loader/lib/loader.js!./~/resolve-url-loader!./src/scss/main.scss
Module not found: Error: Can't resolve '../fonts/roboto/Roboto-Thin.woff2' in 'C:\Users\Myname\Documents\Projects\webpack-test\src\scss'
# ./~/css-loader!./~/sass-loader/lib/loader.js!./~/resolve-url-loader!./src/scss/main.scss 6:75477-75521
# ./src/scss/main.scss
# multi ./src/js/index.js ./src/scss/main.scss
So this is where I am stuck. Why does the compilation work if I require() the Materialize SASS file directly? Why does it fail when I import the Materialize SASS file to my own SASS file? How do I have to change my Webpack config so that it can find the font files?
By accident I found out that materialize offers a variable to set the font path, so adjusting my own SASS file to this solved the problem
$roboto-font-path: "~materialize-css/fonts/roboto/" !default;
#import "~materialize-css/sass/materialize";
// ... my customizations ...
I need to disable AMD on 4 files and load video.js first before loading the other 3 files, because they depend on it. When I tried doing it in webpack.config.js like so:
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: __dirname + '/public',
filename: 'bundle.js'
},
devServer: {
inline: true,
contentBase: './src',
port: 3333
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules|lib/,
loader: 'babel',
query: {
presets: ['es2015', 'react', 'stage-2'],
plugins: ['transform-class-properties']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /[\/\\]lib[\/\\](video|playlist|vpaid|overlay)\.js$/,
exclude: /node_modules|src/
loader: 'imports?define=>false'
}
]
}
}
It doesn't really work, because it just loads video.js (with disabled AMD) and completely ignores the other 3 files.
My folder structure is like so:
▾ lib/
overlay.js
playlist.js
video.js
vpaid.js
▸ node_modules/
▾ public/
200.html
bundle.js
▾ src/
App.js
index.html
main.js
LICENSE
package.json
README.md
webpack.config.js
Now, I found something that takes me 1 step back, because now even video.js doesn't load:
require('imports?define=>false!../lib/video.js')
require('imports?define=>false!../lib/playlist.js')
require('imports?define=>false!../lib/vpaid.js')
require('imports?define=>false!../lib/overlay.js')
and instead just throws these kinds of warnings:
WARNING in ./~/imports-loader?define=>false!./lib/video.js
Critical dependencies:
15:415-422 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/video.js 15:415-422
WARNING in ./~/imports-loader?define=>false!./lib/playlist.js
Critical dependencies:
10:417-424 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/playlist.js 10:417-424
WARNING in ./~/imports-loader?define=>false!./lib/vpaid.js
Critical dependencies:
4:113-120 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/vpaid.js 4:113-120
WARNING in ./~/imports-loader?define=>false!./lib/overlay.js
Critical dependencies:
10:416-423 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
# ./~/imports-loader?define=>false!./lib/overlay.js 10:416-423
So, my question is, how can I make this work in webpack.config.js so that I don't get these warnings?
I have solved the problem! To make this work you need this:
{
test: /[\/\\]lib[\/\\](video|playlist|vpaid|overlay)\.js$/,
exclude: /node_modules|src/
loader: 'imports?define=>false'
}
and this
require('script-loader!../lib/video.js')
require('script-loader!../lib/playlist.js')
require('script-loader!../lib/vpaid.js')
require('script-loader!../lib/overlay.js')
together!
Now, if you use this (instead of script-loader):
require('imports?define=>false!../lib/video.js')
require('imports?define=>false!../lib/playlist.js')
require('imports?define=>false!../lib/vpaid.js')
require('imports?define=>false!../lib/overlay.js')
It's not gonna work! (you need both imports-loader and script-loader working in unison.
When I attempted to use webpack to compile my react jsx code, I received the following error:
ERROR in ./client/index.js
Module parse failed: C:\Users\Gum-Joe\Documents\Projects\bedel/client\index.js Unexpected token (6:11)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (6:11)
at Parser.pp.raise (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:920:13)
at Parser.pp.unexpected (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1483:8)
at Parser.pp.parseExprAtom (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:330:12)
at Parser.pp.parseExprSubscripts (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:225:19)
at Parser.pp.parseMaybeUnary (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:204:17)
at Parser.pp.parseExprOps (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:151:19)
at Parser.pp.parseMaybeConditional (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:133:19)
at Parser.pp.parseMaybeAssign (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:110:19)
at Parser.pp.parseExpression (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:86:19)
at Parser.pp.parseReturnStatement (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1854:26)
at Parser.pp.parseStatement (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1719:19)
at Parser.pp.parseBlock (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:1991:21)
at Parser.pp.parseFunctionBody (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:607:22)
at Parser.pp.parseMethod (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:576:8)
at Parser.pp.parseClassMethod (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:2137:23)
at Parser.pp.parseClass (C:\Users\Gum-Joe\Documents\Projects\bedel\node_modules\acorn\dist\acorn.js:2122:10)
# ./client/index.js 1:0-20
.babelrc:
{
"presets": ["es2015", "react"]
}
webpack.config.js:
// Webpack config
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// Use client as our root
context: __dirname + "/client",
// Entry file
entry: "./index.js",
// Resolve
resolve: {
extensions: ['', '.js', '.jsx']
},
// Output to /build
output: {
path: path.join(__dirname, "build", "js"),
filename: "bundle.js"
},
loaders: [
{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
],
// Plugins
plugins: [
// HTML
new HtmlWebpackPlugin({
title: 'Bedel',
filename: path.join(__dirname, 'views', 'index.ejs'),
template: path.join(__dirname, 'client', 'templates', 'index.ejs')
})
]
};
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render () {
return <p> Hello React</p>;
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
I have installed all the babel presets required, as well as babel-core.
I have looked at the following answers already:
babel-loader jsx SyntaxError: Unexpected token
React, babel, webpack not parsing jsx code
Edit: After commenting out my jsx syntax, the outputting bundle.js does not appear to have been transformed by babel (i.e. I can see ES6 code in it)
Edit: Sorry for the inconvenience, but app.jsx was a solution that I tried that involved putting the logic that should be in index.js into a separate file.
Edit: Here is a list of the solutions I tried that did not work:
Copy .babelrc to client/.babelrc
Change test to test for .js instead of .js
Separate app logic into separate file (app.js)
Put presets to use in webpack config
Also, I have pushed my code to my GitHub repo (https://github.com/Gum-Joe/bedel). Feel free to have a look at it.
You configured the loader to only pass .jsx files through Babel:
test: /\.jsx$/
However, your file has the extension .js. Either rename the file or update the test expression to /\.jsx?$/.
In addition to updating the test, you need to rename .babel.rc to .babelrc (no . before rc). Otherwise Babel thinks that there is no configuration file and won't load any presets.
The loaders property must exist within the module property. Webpack Loaders
module.exports = {
// ...
// Output to /build
output: {
path: path.join(__dirname, "build", "js"),
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
]
},
//...
};
You need to use react-preset with babel, like here:
loaders: [{
test: /\.(js|jsx)$/,
loader: 'babel',
query: {
presets: [
'es2015',
'react'
]
}
}]
I'm having this issue as well, and if you're using Windows and Node 6.x, the only workaround I've found for now seems to be to use Node 4 LTS or 5 instead. Without knowing the root cause, the problem seems to stem from some combination of using JSX, Webpack, Babel, Acorn JS, Node 6, and Windows.
https://github.com/coryhouse/pluralsight-redux-starter/issues/2
https://github.com/danmartinez101/babel-preset-react-hmre/issues/32
Can you try wrapping the entire element in brackets "()"?
return (<p>...</p>)
I'm trying out webpack for the first time and used this tutorial to get started and include react.js.
After finishing the steps and installing the style and css module I keep getting an error that the css module didn't return a function.
This is my index.jsx:
/** #jsx React.DOM */
'use strict';
require('../css/normalize.css');
var React = require('react');
var Hello = require('./Test/Hello');
React.render(<Hello />, document.getElementById('content'));
And my webpack config file:
module.exports = {
entry: './ui/src/index.jsx',
output: {
path: __dirname + '/build-ui',
filename: 'app.js', //this is the default name, so you can skip it
//at this directory our bundle file will be available
//make sure port 8090 is used when launching webpack-dev-server
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.scss$/,
loader: "style!css!sass"
}
]
},
externals: {
//don't bundle the 'react' npm package with our bundle.js
//but get it from a global 'React' variable
'react': 'React'
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};
When webpack tries to bundle the project it always states the following error:
ERROR in Loader /Users/Johannes/Documents/Development/holmes/node_modules/css/index.js didn't return a function
# ./ui/src/index.jsx 5:0-31
I don't know what to do about that. Has anyone encountered that issue? And how can I solve it?
EDIT: My directory looks as follows:
holmes/
ui/
css/
normalize.css
src/
Test/
Hello.jsx
index.jsx
index.html
package.json
webpack.config.js
This error is caused by a css module inside node_modules. Since you've specified the css-loader in your config, webpack tries to lookup that loader inside node_modules and finds another module called css which doesn't look like a loader (hence the error message).
To avoid confusion you should simply add the -loader postfix to each loader. Omitting the -loader postfix is just a convenience feature by webpack, but unfortunately it's the culprit of that error in your case.
loaders: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader"
}
Update: Starting with webpack 2, you can't omit the -loader postfix anymore. We decided to do this to prevent errors like this.
I had a similar issue with react-flexbox-grid. In my case, the solution was installing css-loader and style-loader npm modules:
npm install css-loader style-loader --save-dev
I also came across a similar issue using node-noop.
Fortunately, using null as a replacement worked when I added enzyme and react-addons-test-utils to a project.