Error in Entry module not found and in webpack - javascript

I'm new to JavaScript and follow a clear node-tutorial on Github.
But whatever I've tried in all modules, I keep getting this error message when I run yarn dev:wds
ERROR in Entry module not found: Error: Can't resolve './src' in 'C:\Users\Renate\projects'
ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src Module not found:
Error: Can't resolve './src' in 'C:\Users\Renate\projects' # multi (webpack)-dev-
server/client?http://localhost:8
I've tried this solution, but reinstalling babel-loader 7 did not solve my problem. I've also tried to re-intall the entire webpack-module, but that did not solve my problem either.
My webpack.config.babel.js file:
// #flow
import path from 'path'
import webpack from 'webpack'
import { WDS_PORT } from './src/shared/config'
import { isProd } from './src/shared/util'
export default {
entry: [
'react-hot-loader/patch',
'./src/client',
],
output: {
filename: 'js/bundle.js',
path: path.resolve(__dirname, 'dist/'),
publicPath: isProd ? '/static/' : `http://localhost:${WDS_PORT}/dist/`,
},
module: {
rules: [
{ test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ },
],
},
devtool: isProd ? false : 'source-map',
resolve: {
extensions: ['.js', '.jsx'],
},
devServer: {
port: WDS_PORT,
hot: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
}
My babelrc.json file:
{
"presets": [
"env",
"flow",
"react"
],
"plugins": [
"flow-react-proptypes"
]
}
My package.json file
{
"name": "your-project",
"version": "1.0.0",
"license": "MIT",
"browserslist": [
"> 1%"
],
"scripts": {
"start": "yarn dev:start",
"dev:start": "nodemon -e js,jsx --ignore lib --ignore dist --exec babel-node src/server",
"dev:wds": "webpack-dev-server --progress",
"prod:build": "rimraf lib dist && babel src -d lib --ignore .test.js && cross-env NODE_ENV=production webpack -p --progress",
"prod:start": "cross-env NODE_ENV=production pm2 start lib/server && pm2 logs",
"prod:stop": "pm2 delete server",
"lint": "eslint src webpack.config.babel.js",
"test": "yarn lint && flow && jest --coverage",
"precommit": "yarn test",
"prepush": "yarn test && yarn prod:build"
},
"dependencies": {
"babel-polyfill": "^6.26.0",
"compression": "^1.7.4",
"express": "^4.17.1",
"immutable": "4.0.0-rc.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-hot-loader": "^4.5.3",
"react-redux": "^7.1.3",
"redux": "^4.0.5",
"redux-actions": "^2.6.5"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/node": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"#babel/preset-flow": "^7.8.3",
"#babel/preset-react": "^7.8.3",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-eslint": "^10.0.3",
"babel-jest": "^25.1.0",
"babel-loader": "7",
"babel-plugin-flow-react-proptypes": "^25.1.0",
"babel-preset-env": "^1.7.0",
"babel-preset-flow": "^6.23.0",
"babel-preset-react": "^6.24.1",
"cross-env": "^7.0.0",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-plugin-compat": "^3.5.1",
"eslint-plugin-flowtype": "^4.6.0",
"eslint-plugin-import": "2.18.2",
"eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-react": "^7.18.3",
"eslint-plugin-react-hooks": "1.7.0",
"flow-bin": "^0.118.0",
"husky": "^4.2.1",
"jest": "^25.1.0",
"nodemon": "^2.0.2",
"pm2": "^4.2.3",
"rimraf": "^3.0.2",
"webpack": "^4.41.6",
"webpack-babel-env-deps": "^1.6.3",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.3"
},
"type": "module"
}
My eslintrc.json file
{
"extends": [
"airbnb",
"plugin:flowtype/recommended"
],
"plugins": [
"flowtype",
"compat"
],
"env": {
"browser": true,
"jest": true
},
"rules": {
"semi": [2, "never"],
"no-unexpected-multiline": 2,
"compat/compat": 2,
"linebreak-style": [2, "windows"]
},
"parser": "babel-eslint"
}
for reference, please find attached snapshot of my folder structure here.
And if you check this Github page or this, you will see there are more with the same problem, but no solution worked for me so far. Hope you can help me!
update
I've also tried the suggestion of Alex (see answer here below), did not work.
...
entry: [
'react-hot-loader/patch',
path.resolve(__dirname, './src/client')
],
...

Just a suggestion: have you tried resolving the problematic path before passing it to webpack? Something along the lines: path.resolve(__dirname, './src/client') will convert the path from relative to absolute and often times it helps to quiet various loaders.
...
entry: [
'react-hot-loader/patch',
path.resolve(__dirname, './src/client'),
],
...

I checked your repo and I solved the webpack issue. the main issue was everytime you imported a jsx file, you need to write the extention as jsx. and also there were some errors inside components so some of the components were not resolved. here is one in button.jsx
// type Props = {
// label: string,
// handleClick: Function,
// }
and also since implementation of many packages changed, bundle.js is giving error. for example for react hot reload package, there is no need to import this :
import { AppContainer } from 'react-hot-loader'
check the documentation.
also many babel packages were old version. so i Installed the new packages. you can check the package.json.
implementation of webpack config was also wrong. in webpack.config.js entry point takes relative path but output point takes absolute path. I organized the webpack.config.js.
this project also implements server-side code but for this, you need another webpack.config.js for dev. and also for server-side rendering, you need to use ReactDOM.hydrate and also there are too many important things that this project did not implement. here is the repo:
modified repo

Related

Browser will not Launch on npm start with webpack Related to webpack-dev-middleware#3.7.2 and webpack#^4.0.0 Peer Dependency Issue?

I am brand new to JavaScript. In an attempt to learn JavaScript, I cloned the webpack-starter project from GitHub (https://github.com/wbkd/webpack-starter). Then, I ran a npm install in the clone folder on my desktop, and then I ran a npm audit fix upon seeing a found 1 low severity vulnerability message in the Git Bash console. Then, I saw this message, npm WARN webpack-dev-middleware#3.7.2 requires a peer of webpack#^4.0.0 but none is installed. You must install peer dependencies yourself.
Before investigating the above warning, I ran a npm start in PowerShell from the project folder. I received no error messages, but my browser (Chrome) never launched.
Then, I investigated the npm WARN message and found this, https://stackoverflow.com/a/64733624/9698039, which led me to this, https://github.com/webpack/webpack-dev-server/issues/2807#issuecomment-734982609, which led me to the decision to downgrade my version of webpack from ^5.10.0 to "webpack": "^4.0.0".
Before downgrading, here was my package.json:
{
"name": "webpack-starter",
"version": "1.0.0",
"description": "A light foundation for your next frontend project based on webpack.",
"scripts": {
"lint": "npm run lint:styles; npm run lint:scripts",
"lint:styles": "stylelint src",
"lint:scripts": "eslint src",
"build": "cross-env NODE_ENV=production webpack --config webpack/webpack.config.prod.js",
"start": "webpack serve --config webpack/webpack.config.dev.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/wbkd/webpack-starter.git"
},
"keywords": [
"webpack",
"startkit",
"frontend",
"es6",
"javascript",
"webdev"
],
"author": "webkid.io",
"license": "MIT",
"bugs": {
"url": "https://github.com/wbkd/webpack-starter/issues"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/preset-env": "^7.12.7",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^6.4.0",
"cross-env": "^7.0.3",
"css-loader": "^5.0.1",
"eslint": "^7.15.0",
"eslint-loader": "^4.0.2",
"file-loader": "^6.2.0",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^4.5.0",
"mini-css-extract-plugin": "^1.3.2",
"node-sass": "^5.0.0",
"postcss-loader": "^4.1.0",
"sass-loader": "^10.1.0",
"style-loader": "^2.0.0",
"stylelint": "^13.8.0",
"stylelint-config-standard": "^20.0.0",
"stylelint-webpack-plugin": "^2.1.1",
"webpack": "^5.10.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0",
"webpack-merge": "^5.4.0"
},
"dependencies": {
"#babel/polyfill": "^7.12.1",
"core-js": "^3.8.1"
}
}
And here was my webpack.config.dev.js:
const Path = require('path');
const Webpack = require('webpack');
const { merge } = require('webpack-merge');
const StylelintPlugin = require('stylelint-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'development',
devtool: 'eval-cheap-source-map',
output: {
chunkFilename: 'js/[name].chunk.js',
},
devServer: {
inline: true,
hot: true,
},
plugins: [
new Webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
new StylelintPlugin({
files: Path.join('src', '**/*.s?(a|c)ss'),
}),
],
module: {
rules: [
{
test: /\.js$/,
include: Path.resolve(__dirname, '../src'),
enforce: 'pre',
loader: 'eslint-loader',
options: {
emitWarning: true,
},
},
{
test: /\.html$/i,
loader: 'html-loader',
},
{
test: /\.js$/,
include: Path.resolve(__dirname, '../src'),
loader: 'babel-loader',
},
{
test: /\.s?css$/i,
use: ['style-loader', 'css-loader?sourceMap=true', 'postcss-loader', 'sass-loader'],
},
],
},
});
To downgrade webpack, I changed "webpack": "^5.10.0" to "webpack": "^4.0.0" in the package.json and then ran npm install from Git Bash again.
Then, I ran npm start from PowerShell once again, and once again I see no error message, and I see the Compiled successfully message, but once again the browser does not launch. It appears as if the webpack peer dependency issue is unrelated to the failure of browser to launch issue, but I am new to JavaScript and therefore currently unable to make that claim with 100% confidence.
So, I looked around some more and found this, https://stackoverflow.com/a/39753225/9698039, so I added open: true to devServer in the webpack.config.dev.js, resulting in this,
devServer: {
inline: true,
hot: true,
open: true
}
And that worked! My browser launched. I'm still not sure if I could have used webpack without downgrading, but it seems like the browser launch issue is unrelated to the peer dependency issue.

Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Cannot find module 'babel-core'

I have been programming a database that is linked to React, but after a while I installed a library that is babel-core and other libraries, but always when compiling I get an error that is the following:
ERROR in ./src/app/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-core'
{
"name": "Mern-Stack-Example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon node src/app.js",
"webpack": "webpack --mode development"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
//These
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/node": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-loader": "^7.1.5",
"nodemon": "^2.0.7",
"webpack": "^5.17.0",
"webpack-cli": "^4.4.0"
},
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"mongoose": "^5.11.13",
"morgan": "^1.10.0",
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
But I have changed it and the error keeps appearing, I don't know how to solve it, if someone knows please help me
Webpack.Confg:
module.exports = {
entry: './src/app/index.js',
output: {
path: __dirname + '/src/public/js',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
};
And .Babel
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
Remove your node_modules and follow these steps:
npm install --save-dev #babel/core #babel/cli #babel/preset-env #babel/node
Then, check the existence of these files:
node_modules/.bin/babel-node
node_modules/.bin/babel-node.cmd - windows only
node_modules/#babel/node/bin/babel-node.js
Generally, these issues might come in due to the version conflicts. Try to install nvm and use lesser node version. Also, you should use previous versions of babel packages
#babel/preset-env
#babel/preset-react

webpack production mode "build" - force browser not to read cached file/rebuild fresh files

We have an application (a website) with some React components, css and js compiled with webpack.
Our workflow is to npm run start in the /src/ folder while developing locally, which generates CSS and JS files in /dist/ then run npm run build to clear down refresh all the files in the /dist/ folder before deploying to live. That is the intent, anyway.
The problem is, when we deploy a change to the live environment, it seems the browser still has previous versions of the CSS/JS files cached, or not reading correctly from the new versions. This only happens with the hashed/chunked (React component) files (see ** in file structure below), not the main.js or main.scss file.
We thought webpack produced new 'chunks'/files with each build. Is there a way we can force webpack to do this so the files are read as new when they change, or the filenames are different? I do want the files to be cached by the browser, but I also want new changes to be accounted for.
Example File Structure
--/src/
----/scss/
------main.scss
----/js/
------main.js (imports js components)
------/components/
--------banner.js
--------ReactComponent.jsx (imports ReactComponent.scss)
--------ReactComponent.scss
--/dist/
----/css/
------main.css
------2.css (react component css) (**)
------6.css (react component css) (**)
----/js/
------main.js
------0_39cd0323ec029f4edc2f.js (react component js) (**)
------1_c03b31c54dc165cb590e.js (react component js) (**)
** these are the files that seem to get cached or not read properly when changes are made.
webpack.config.js
const webpack = require("webpack");
const path = require("path");
const autoprefixer = require("autoprefixer");
const TerserJSPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = {
entry: {
main: ["./js/main.js", "./scss/main.scss"],
},
output: {
filename: "js/[name].js",
chunkFilename: "js/[name]_[chunkhash].js",
path: path.resolve(__dirname, "../dist/"),
publicPath: "/app/themes/[package]/dist/",
jsonpFunction: "o3iv79tz90732goag"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(sass|scss|css)$/,
exclude: "/node_modules/",
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
importLoaders: 2,
sourceMap: true
}
},
{
loader: "postcss-loader",
options: {
plugins: () => [require("precss"), require("autoprefixer")],
sourceMap: true
}
},
{
loader: "sass-loader",
options: {
sourceMap: true,
includePaths: [path.resolve(__dirname, "../src/scss")]
}
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ["file-loader"]
}
]
},
optimization: {
minimizer: [
new TerserJSPlugin({
cache: true,
parallel: true,
sourceMap: true
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
safe: true,
zindex: false,
discardComments: {
removeAll: true
}
},
canPrint: true
})
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "css/[name].css",
chunkFilename: "css/[id].css"
})
]
};
package.json
{
"name": "packagename",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "(rm -rf ./../dist/*) & webpack --mode production",
"start": "webpack --mode development --watch "
},
"keywords": [],
"author": "Sarah",
"license": "ISC",
"browserslist": [
"last 4 versions"
],
"devDependencies": {
"#babel/core": "^7.9.0",
"#babel/plugin-proposal-object-rest-spread": "^7.9.5",
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/plugin-transform-arrow-functions": "^7.2.0",
"#babel/plugin-transform-classes": "^7.9.5",
"#babel/plugin-transform-flow-strip-types": "^7.9.0",
"#babel/plugin-transform-react-jsx": "^7.9.4",
"#babel/preset-env": "^7.9.5",
"#babel/preset-flow": "^7.9.0",
"#babel/preset-react": "^7.0.0",
"autoprefixer": "^7.1.1",
"babel-loader": "^8.1.0",
"babel-plugin-transform-es2015-shorthand-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"browser-sync": "^2.26.7",
"browser-sync-webpack-plugin": "^2.2",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^3.5.3",
"cssnano": "^4.1.10",
"mini-css-extract-plugin": "^0.8.2",
"node-sass": "^4.14.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^2.0.5",
"precss": "^4.0.0",
"resolve-url-loader": "^2.0.2",
"sass-loader": "^6.0.5",
"terser-webpack-plugin": "^2.3.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"dependencies": {
"axios": "^0.19.2",
"body-scroll-lock": "^2.7.1",
"can-autoplay": "^3.0.0",
"debounce": "^1.0.2",
"file-loader": "^5.1.0",
"lazysizes": "^4.1.8",
"moment": "^2.24.0",
"objectFitPolyfill": "^2.3.0",
"promise-polyfill": "^8.1.3",
"react": "^16.9.0",
"react-content-loader": "^5.0.4",
"react-device-detect": "^1.12.1",
"react-dom": "^16.9.0",
"react-html-parser": "^2.0.2",
"react-intersection-observer": "^8.26.2",
"react-moment": "^0.9.7",
"react-pdf": "^4.1.0",
"scrollmonitor": "^1.2.4",
"socket.io": "^2.3.0"
}
}
In order to bust a cache on a build, you need to change the url of static asset (js / css).
The best way to do so is to generate random string based on content of the file (called hash), the benefit of this approach is that if the final file didn't changed between deploys it will generate the same hash => clients will use the cached file. If it does changed => hash changed => file name change => clients will fetch a new file.
Webpack has a built it method for this.
// webpack.config.js
module.exports = {
entry: {
main: ["./js/main.js", "./scss/main.scss"],
},
output: {
filename: process.env.NODE_ENV === 'production'? "js/[name]-[hash].js": "js/[name].js", // this will attach the hash of the asset to the filename when building for production
chunkFilename: "js/[name]_[chunkhash].js",
path: path.resolve(__dirname, "../dist/"),
publicPath: "/app/themes/[package]/dist/",
jsonpFunction: "o3iv79tz90732goag"
},
...
}
Edit:
In order to update your HTML file with the new filename (which now will contain hash) you can use HTMLWebpackPlugin which was created specifically for this purpose.
It supports custom template if you need to provide your own html, or creating one. Review the docs.
Just a small update over brilliant #felixmosh solution.
For Webpack 5.x I'm using this:
//webpack.prod.js
const webpackConfig = {
module: {
...
},
output: {
filename: '[name]-[contenthash].js',
chunkFilename: '[name]_[contenthash].js',
},
[contenthash] looks better then [hash] - contenthash only changes when the content of the asset actually changes. I wonder why this is not the default setting for Webpack ?
I love you guys #felixmosh #Sarah for figuring this out !

Webpack production version of website points to the wrong directories

I have two npm commands "build": "webpack --mode production" and "start": "webpack-dev-server --mode development --open". When I run the start command the web application runs as intended with all the CSS and javascript being transpiled correctly.
However when I run build the fils are generated as intended and when the main HTML file is opened the href and src do not point to the correct directories.
I looked at my webpack.config.js and it appears to be working as intended which leads me to a bit of head-scratching. Changing the HTML template causes the development version to break and have the production version work as intended. The intention is for both development and production version to work as intended.
For reference here is my directory structure:
root
|-.vscode
|-dist
| |-css
| |-img
| |-js
| |- output location for bundle.js index.html main.css
|-node.modules
|-src
|-css
| |-scss
|-js
| |-JSON
| |-models
| |-view
| |-app.js
|-index.html
|-.babelrc
|-package-lock.json
|-package.json
|-webpack.config.js
Webpack config file
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const babelLoader = require("babel-loader");
module.exports = {
entry: [
"babel-polyfill","./src/js/app.js"
],
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "bundle.js",
},
devServer: {
contentBase: "./dist"
},
plugins: [
new MiniCssExtractPlugin(),
new HtmlWebpackPlugin({
filename:"index.html",
template:"./src/index.html"
})
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.scss$/,
use: [{
loader: MiniCssExtractPlugin.loader
},
{
loader: "css-loader",
options: {
sourceMap: true,
modules: true,
localIdentName: "[local]"
}
},
"sass-loader"
]
}
]
}
}
and package.json
{
"name": "tempName",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "Fake Name",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.7.2",
"#babel/preset-env": "^7.7.1",
"babel-loader": "^8.0.6",
"chart.js": "^2.9.3",
"css-loader": "^2.1.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"gulp-babel": "^8.0.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.7.0",
"node-sass": "^4.13.0",
"sass-loader": "^7.3.1",
"sortablejs": "^1.10.1",
"style-loader": "^0.23.1",
"url-loader": "^1.1.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"dependencies": {
"axios": "^0.19.0",
"babel-polyfill": "^6.26.0",
"pokedex-promise-v2": "^3.2.0"
}
}
How do I specify the href(s) and src(s) in the HTML document to link to the CSS and javascript since they are added during the build script and are not in the HTML template?
Try these things:
1) instead of setting contentBase to dev-server try to set 'publicPath: '/'
2) set 'output.publicPath' to '/' also
3) if previous doesn't work, HtmlWepbpackPlugin has base option to add prefix for loaded scripts. but i strongly recommend to handle it with public path.
PS: fix your prod build, and only when fix webpack-dev-server. it will be easier

Error: Bootstrap's JavaScript requires jQuery, using Webpack

I'm new to webpack, but I started using it in one of my projects to learn about it.
I would like to use jQuery with Bootstrap, however, when I launch the app, I'm getting the following error:
bootstrap.min.js?5802:6Uncaught Error: Bootstrap's JavaScript requires jQuery
In my webpack config, I have defined two entry points, one for libraries of the project and one for the external ones, called vendors, like jQuery, Bootstrap, etc.
In vendors, I have defined the Bootstrap library after the jQuery library, but I cannot get rid of the error. Any clues of what I'm missing?
This is my webapp config:
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import autoprefixer from 'autoprefixer';
let node_dir = __dirname + '/node_modules';
export default {
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
'jquery': node_dir + '/jquery/dist/jquery.js',
'jquery-validation': node_dir + '/jquery-validation/dist/jquery.validate.js',
'bootstrap': node_dir + '/bootstrap/dist/js/bootstrap.min.js'
}
},
debug: true,
devtool: 'cheap-module-eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
entry: {
// must be first entry to properly set public path
app: ['./src/webpack-public-path',
'webpack-hot-middleware/client?reload=true',
'./src/index'],
vendors: ['jquery','jquery-validation','bootstrap']
},
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: `${__dirname}/src`, // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom)
__DEV__: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS.
//template: 'src/index.ejs',
template: 'src/index.html',
minify: {
removeComments: true,
collapseWhitespace: true
},
inject: true
}),
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"windows.jQuery": "jquery"
}),
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel']},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loaders: ['style', 'css?sourceMap', 'postcss', 'sass?sourceMap']}
]
},
postcss: ()=> [autoprefixer]
};
And this is my package.json file:
{
"name": "dario-webapplication",
"version": "1.0.0",
"description": "Webapplication for Dario project",
"engines": {
"npm": ">=3"
},
"scripts": {
"preinstall": "node tools/nodeVersionCheck.js",
"setup": "node tools/setup/setupMessage.js && npm install && node tools/setup/setup.js",
"remove-demo": "babel-node tools/removeDemo.js",
"start-message": "babel-node tools/startMessage.js",
"prestart": "npm-run-all --parallel start-message remove-dist",
"start": "npm-run-all --parallel open:src lint:watch",
"open:src": "babel-node tools/srcServer.js",
"open:dist": "babel-node tools/distServer.js",
"lint": "esw webpack.config.* src tools --color",
"lint:watch": "npm run lint -- --watch",
"clean-dist": "npm run remove-dist && mkdir dist",
"remove-dist": "rimraf ./dist",
"prebuild": "npm run clean-dist && npm run lint && npm run test",
"build": "babel-node tools/build.js && npm run open:dist",
"test": "mocha tools/testSetup.js \"src/**/*.spec.js\" --reporter progress",
"test:cover": "babel-node node_modules/isparta/bin/isparta cover --root src --report html node_modules/mocha/bin/_mocha -- --require ./tools/testSetup.js \"src/**/*.spec.js\" --reporter progress",
"test:cover:travis": "babel-node node_modules/isparta/bin/isparta cover --root src --report lcovonly _mocha -- --require ./tools/testSetup.js \"src/**/*.spec.js\" && cat ./coverage/lcov.info | node_modules/coveralls/bin/coveralls.js",
"test:watch": "npm run test -- --watch",
"open:cover": "npm run test:cover && open coverage/index.html"
},
"author": "Francisco Jose Parra Gonzalez",
"license": "MIT",
"dependencies": {
"bootstrap": "3.3.7",
"jquery": "2.1.4",
"jquery-validation": "1.15.1",
"object-assign": "4.1.0",
"react": "15.3.0",
"react-bootstrap": "0.30.3",
"react-dom": "15.3.0",
"react-redux": "4.4.5",
"react-router": "2.6.1",
"react-router-redux": "4.0.5",
"redux": "3.5.2",
"redux-thunk": "2.1.0"
},
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-cli": "6.11.4",
"babel-core": "6.11.4",
"babel-loader": "6.2.4",
"babel-plugin-react-display-name": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.2.9",
"babel-preset-es2015": "6.9.0",
"babel-preset-react": "6.11.1",
"babel-preset-react-hmre": "1.1.1",
"babel-preset-stage-1": "6.5.0",
"babel-register": "6.11.6",
"browser-sync": "2.14.0",
"chai": "3.5.0",
"chalk": "1.1.3",
"connect-history-api-fallback": "1.2.0",
"coveralls": "2.11.12",
"cross-env": "2.0.0",
"css-loader": "0.23.1",
"enzyme": "2.4.1",
"eslint": "3.2.2",
"eslint-plugin-import": "1.12.0",
"eslint-plugin-jsx-a11y": "2.0.1",
"eslint-plugin-react": "6.0.0",
"eslint-watch": "2.1.14",
"extract-text-webpack-plugin": "1.0.1",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.22.0",
"isparta": "4.0.0",
"mocha": "3.0.1",
"mockdate": "1.0.4",
"node-sass": "3.8.0",
"npm-run-all": "2.3.0",
"open": "0.0.5",
"postcss-loader": "0.9.1",
"prompt": "1.0.0",
"react-addons-test-utils": "15.3.0",
"redux-immutable-state-invariant": "1.2.3",
"replace": "0.3.0",
"rimraf": "2.5.4",
"sass-loader": "4.0.0",
"sinon": "1.17.5",
"sinon-chai": "2.8.0",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"webpack": "1.13.1",
"webpack-dev-middleware": "1.6.1",
"webpack-hot-middleware": "2.12.2",
"webpack-md5-hash": "0.0.5"
},
"keywords": [],
"repository": {
"type": "git",
"url": ""
}
}
I finally got rid of the error just by adding a new entry in the ProvidePlugin:
jQuery:"jquery"
so finally the plugin looks like this:
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"window.jQuery": "jquery",
jQuery:"jquery"
})
I leave it here in case someone else faces the same problem.
Using Create React App you can import like this:
import 'jquery/src/jquery';
import '../node_modules/bootstrap-sass/assets/javascripts/bootstrap.min';
note: This is for jQuery 3.*
Bootstrap requires jquery to be available on the global object. Try the below -
import 'bootstrap/dist/css/bootstrap.min.css';
const $ = require('jquery');
window.$ = $;
window.jQuery = $;
require('bootstrap/dist/js/bootstrap.min');
This is verified for bootstrap#3.3.7 and jquery#2.2.4.
Ref - issue
You can also add the Expose Loader package:
npm install expose-loader --save-dev
And use in your webpack entry point (ie. main.js) like this:
import 'expose?$!expose?jQuery!jquery'
// ...

Categories

Resources