How to include jQuery UI into my project using Webpack? - javascript

I started a new project using React Slingshot and am trying to use jQuery UI accordions. I have installed the jQuery UI plugin with NPM using npm install --save jquery-ui. As far as I understand, Webpack automatically bundles my Javascript into a bundles.js based on my Webpack config, and is included on my index.ejs page. However, I'm getting this error, which tells me that the jQuery UI plugin is not being loaded to the page:
Uncaught TypeError: $(...).accordion is not a function
How can I include this plugin? Below I have included my code - let me know if there are any other files you'd like to see.
index.ejs:
<!DOCTYPE html>
<html lang="en">
<!--
**NOTE:** This is a template for index.html. It uses ejs and htmlWebpackPlugin to generate a different index.html for each environment. htmlWebpackPlugin will dynamically add references to the scripts and styles that it bundles to this file. The generated bundles have hash-based filenames, so it's necessary to add the references dynamically.
For more info on ejs, see http://www.embeddedjs.com/. For examples of using it with htmlWebpackPlugin, see https://github.com/jaketrent/html-webpack-template/blob/master/index.ejs
-->
<head>
<% if (htmlWebpackPlugin.options.trackJSToken) { %>
<script>window._trackJs = {token: '<%= htmlWebpackPlugin.options.trackJSToken %>'};</script>
<script src="https://d2zah9y47r7bi2.cloudfront.net/releases/current/tracker.js"></script>
<% } %>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8"/>
<title>Fusion Starter</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
index.js:
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
import App from './components/App';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import './styles/spa.less';
import './styles/jquery-ui.min.css';
import './styles/jquery-ui.structure.min.css';
import './styles/jquery-ui.theme.min.css';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('app')
);
App.js:
import React, { PropTypes } from 'react';
import Header from './common/Header';
const App = () => {
return (
<div>
<Header />
<div id="content" className="ui-front">
<div id="appContainer">
<div id="accordionContainer">
<div id="accordion">
<h3 id="accountDetailsPanel">SELECT STATE AND ACCOUNT TYPE</h3>
<div id="accountDetailsContainer" className="inner-content"></div>
</div>
</div>
</div>
</div>
</div>
);
};
$(document).ready(function () {
$("#accordion").accordion({ header: "h3",
autoheight: false,
active: false,
alwaysOpen: false,
fillspace: false,
collapsible: true,
//heightStyle: 'content' //auto, fill, content
});
});
export default App;
package.json:
{
"name": "practice",
"version": "0.1.0",
"description": "",
"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 test:watch 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": "",
"license": "MIT",
"dependencies": {
"jquery": "3.1.0",
"jquery-ui": "1.12.0",
"object-assign": "4.1.0",
"react": "15.2.0",
"react-dom": "15.2.0",
"react-redux": "4.4.5",
"react-router-redux": "4.0.5",
"redux": "3.5.2"
},
"devDependencies": {
"babel-cli": "6.10.1",
"babel-core": "6.10.4",
"babel-loader": "6.2.4",
"babel-plugin-react-display-name": "2.0.0",
"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.9.0",
"browser-sync": "2.13.0",
"chai": "3.5.0",
"chalk": "1.1.3",
"coveralls": "2.11.11",
"cross-env": "1.0.8",
"css-loader": "0.23.1",
"enzyme": "2.4.1",
"eslint": "3.0.1",
"eslint-plugin-import": "1.10.2",
"eslint-plugin-jsx-a11y": "1.5.5",
"eslint-plugin-react": "5.2.2",
"eslint-watch": "2.1.13",
"extract-text-webpack-plugin": "1.0.1",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.22.0",
"isparta": "4.0.0",
"less": "2.7.1",
"less-loader": "2.2.3",
"mocha": "2.5.3",
"node-sass": "3.8.0",
"npm-run-all": "2.3.0",
"open": "0.0.5",
"prompt": "1.0.0",
"react-addons-test-utils": "15.2.0",
"redux-immutable-state-invariant": "1.2.3",
"replace": "0.3.0",
"rimraf": "2.5.3",
"sass-loader": "4.0.0",
"sinon": "1.17.4",
"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.1",
"webpack-md5-hash": "0.0.5"
},
"keywords": [],
"repository": {
"type": "git",
"url": ""
}
}
webpack.config.dev.js:
import webpack from 'webpack';
import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
export default {
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: [
'webpack-hot-middleware/client?reload=true',
'./src/index'
],
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: 'http://localhost:3000/', // Use absolute paths to avoid the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob. Note: Only necessary in Dev.
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.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS.
template: 'src/index.ejs',
minify: {
removeComments: true,
collapseWhitespace: true
},
inject: true
})
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff"},
{test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=image/svg+xml'},
{test: /\.(jpe?g|png|gif)$/i, loaders: ['file']},
{test: /\.ico$/, loader: 'file-loader?name=[name].[ext]'},
{test: /\.css$/, loaders: ['style', 'css?sourceMap']},
{test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap']},
{test: /\.less$/, loaders: ['style', 'css?sourceMap', 'less?sourceMap']}
]
}
};

I had a similar problem and it worked for me:
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
// ...
alias: {
jquery: 'jquery/src/jquery',
'jquery-ui': 'jquery-ui/ui',
},

I'm still new to webpack, but https://stackoverflow.com/a/39230057/1798643 worked for me:
npm i -S jquery-ui-bundle
Then use:
require("jquery-ui-bundle");
If you try to alias jquery-ui module, you're in for trouble since its in:
./build/release.js
Which you can alias in webpack config:
alias: {
"jquery-ui": "jquery-ui/build/release.js",
...
But that will lead to more trouble since its inner requires will not be resolved:
Module not found: Error: Cannot resolve module 'shelljs'
Module not found: Error: Cannot resolve module 'download.jqueryui.com/lib/jquery-ui'
Module not found: Error: Cannot resolve module 'node-packager'
And so on...

I solved this issue by setting gloabl variables window.$ and window.jQuery after plugin functions were imported:
import $ from 'jquery';
import 'webpack-jquery-ui'
import 'webpack-jquery-ui/css'
//console.log($.ui.dialog) //check new plugin function
window.$ = window.jQuery = $;
It also works when you need more jQuery plugin, such as jstree, datatables, e.g.
import $ from 'jquery';
import 'webpack-jquery-ui'
import 'jstree'
//console.log($.fn.jstree) //check new plugin function
window.$ = window.jQuery = $;
The tip is window.$ = window.jQuery = $; after plugin were imported. Otherwise you would see $.ui.dialog is defined in main.js, but it is undefined in other script files

Related

Webpack 5 React component library UMD bundle with SourceMaps

I am attempting to make a webpack 5 build process to create a react component library I just had a couple of things cannot seem to get working.
#1) The webpack build command works fine, and when using the inline-source-map option I can
SEE the data URL embeded in the outputted build file but when I ever I attempt to publish and test this library on NPM I always get obfuscated errors without original lines of code so I can't even tell where the errors are; what else am I missing to activate source-maps? I am using Chrome dev tools and it doesn't even tell me a source map is available for that code...
#2) Another issue I am having is after building this with webpack into the dist folder; I start another CRA test app and try to pull components out of the built library but all I get are these errors.
./src/dist/index.js
Line 1:1: Expected an assignment or function call and instead saw an expression no-unused-expressions
Line 1:112: 'define' is not defined no-undef
Line 1:123: 'define' is not defined no-undef
Line 1:190: Unexpected use of 'self' no-restricted-globals
Line 1:466: Expected an assignment or function call and instead saw an expression no-unused-expressions
Line 1:631: Expected an assignment or function call and instead saw an expression no-unused-expressions
I am aware webpack 5 stopped bundling polyfills for Node but shouldn't this code run
if I place it in the src directory of a CRA application? This is bundled code shouldn't it work in the browser/ in another React application? I targeted UMD so I thought it would work in this environment
here is all the necessary info
Webpack.config.js
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry: "./src/index.js",
devtool: "inline-source-map",
externals: [nodeExternals()],
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
library: {
name: "test",
type: "umd",
},
},
plugins: [new CleanWebpackPlugin()],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"],
},
},
},
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"],
include: path.resolve(__dirname, "./src"),
},
],
},
};
Package.json
{
"name": "test-lib",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "start-storybook",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"#babel/preset-react": "^7.14.5",
"#storybook/addon-knobs": "^6.3.1",
"#storybook/react": "^6.3.10",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^4.0.0",
"node-sass": "^6.0.1",
"path": "^0.12.7",
"sass-loader": "^12.1.0",
"webpack": "^5.58.0",
"webpack-cli": "^4.9.0",
"webpack-node-externals": "^3.0.0"
}
}
Button.js (sample component)
import React from 'react'
import PropTypes from 'prop-types';
const Button = ({message = 'Hello world'}) => (
<button>{message}</button>
)
Button.propTypes = {
message: PropTypes.string.isRequired
}
export default Button
Build entry point (index.js)
export { default as Button } from "./components/Button";

webpack bundles files but index.js isn't running

I have an index.js file that imports my CSS and a few packages, but after bundling everything and starting the server I noticed that index.js wasn't running. I did a simple console.log in index.js and it isn't reached.
I copied the contents of my webpack.config file from a previous project which was working correctly, so I'm not sure if it's a file structure/path error or what not. Any thoughts?
Directory structure:
webpack.config.js:
const path = require('path')
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin')
var $ = require("jquery");
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'RecruitmentTracking.txt',
inject: 'body'
});
module.exports = {
entry: "./src/index.js", // removing the . fails the build
output: {
filename: './SiteAssets/scripts/RecruitmentTracking.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader']
}, {
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
],
},
devServer: {
disableHostCheck: true
},
devtool: 'cheap-module-eval-source-map', // this helps the browser point to the exact file in the console, helps in debug
devServer: {
contentBase: path.join(__dirname, 'src'),
historyApiFallback: true // this prevents the default browser full page refresh on form submission and link change
},
plugins: [
HtmlWebpackPluginConfig,
new webpack.ProvidePlugin({
"$": "jquery",
"jQuery": "jquery",
"window.jQuery": "jquery"
})]
}
index.js:
import "./RecruitmentTracking.css";
import 'jquery';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import 'jquery-ui-bundle/jquery-ui.min.js';
console.log('this is index.js');
package.json:
{
"name": "recruitmenttracking",
"version": "1.0.0",
"description": "Recruitment Initiatives Tracking",
"main": "index.js", // ----- should a more specific file path be here?
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --open --mode development",
"build": "webpack --config webpack.config.js",
"dev-server": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
},
"dependencies": {
"#babel/polyfill": "^7.4.0",
"axios": "^0.18.0",
"bootstrap": "^4.3.1",
"jquery": "^3.3.1",
"jquery-ui-bundle": "^1.12.1-migrate",
"pdfmake": "^0.1.54",
"popper": "^1.0.1"
}
}
What's happening here is:
1 - webpack compiles and outputs into: './SiteAssets/scripts/RecruitmentTracking.js'
2 - HtmlWebpackPlugin, will then read the template file './src/index.html', and inject RecruitmentTracking.js script inside the body.
3 - then, it outputs the result to dist/RecruitmentTracking.txt
I don't see any problem, apart from the file being a .txt and not .html. and would obviously not be interpreted by the browser.
Try outputting to an html file instead, it should work
1) For some reason you've configured the following plugin to output a .txt file. So don't expect the browser to intepret that as a html file
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'RecruitmentTracking.txt',
inject: 'body'
});
2) Also I believe that file that you're opening in the browser is /dist/index.html and that file doesn't load your js file. Try adding the following line into /dist/index.html:
<script src"./SiteAssets/scripts/RecruitmentTracking.js"></script>
3) If the above works, please still consider taking a closer look at (1)
You have named the output file in HtmlWebpackPluginConfig as RecruitmentTracking.txt. change it to index.html and it should work
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html', // webpack takes ./src/index.html as input file
filename: 'index.html', // webpack processes the above input template and should output to index.html
inject: 'body'
});

react, wepack, babel, node, npm start error

ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '#babel/preset-es2015' from 'F:\reactapp'
at Function.module.exports [as sync] (F:\reactapp\node_modules\resolve\lib\sync.js:43:15)
at resolveStandardizedName (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:101:31)
at resolvePreset (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:58:10)
at loadPreset (F:\reactapp\node_modules#babel\core\lib\config\files\plugins.js:77:20)
at createDescriptor (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:154:9)
at items.map (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:109:50)
at Array.map ()
at createDescriptors (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:109:29)
at createPresetDescriptors (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:101:10)
at passPerPreset (F:\reactapp\node_modules#babel\core\lib\config\config-descriptors.js:58:96)
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./main.js main[2]
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 448 bytes {0} [built]
[./node_modules/lodash/lodash.js] 527 KiB {0} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
[./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
i ?wdm?: Failed to compile.
Terminate batch job (Y/N)?
package.json file:
package json file is as follows. I followed https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
{
"name": "reactapp",
"version": "1.0.0",
"description": "demo project",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"keywords": [
"[]"
],
"author": "manjunathan g",
"license": "ISC",
"dependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.2.2",
"#babel/preset-react": "^7.0.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.2.3",
"#babel/preset-env": "^7.2.3",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0"
}
}
babel config:
Babel config file is as below; followed as per https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm
{
"presets":["env", "react"]
}
webpack config
webpack config is as follows:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/react', '#babel/es2015'],
plugins: ['#babel/proposal-class-properties']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
The #babel/preset-es2015 package has been deprecated and you can no longer install it from NPM.
The recommendation now is to use #babel/preset-env instead.
There are a lot of mistakes in your file configuration. Let me try to solve it:
.babelrc
You don't need the following devDependencies: babel-core, babel-preset-env, babel-preset-react and babel-preset-es2015. They are deprecated since Babel 7 was realeased. Substitute your code to this:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
webpack.config.js
Since webpack 4 was released, you don't need to inform the entry and output fields (You can do it for custom configurations). By default, webpack will look for index.js file located in the src/ directory (this directory must be in the root of your project). Webpack will create the module dependency graph from this file and output the bundled file to the dist/ directory. Try to configure your webpack.config.js like this:
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
module: {
rules: [
{
test: /\.jsx$/,
exclude: /node_modules/,
use: { loader: "babel-loader" }
},
{
test: /\.html$/,
use: { loader: "html-loader" } //Install it: 'npm i -D html-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "src/index.html" // Put the index.html in the src/ directory
})
]
}
I'm not an expert in configuring webpack and I don't know if I could help you. I wrote an article on medium setting the environment to work with react, babel and webpack, but it is in portuguese. If you want to check: https://medium.com/#brunonakayabu/react-webpack-e-babel-configurando-o-ambiente-de-desenvolvimento-c7ee8a994222

Webpack css-loader: "Module not found: Error: Can't resolve 'main.css' in ..."

I am trying to include my css in the server hosted by webpack-dev-server. For that to happen, I apparently have to use style-loader and css-loader together, in order to bundle the css into the JavaScript.
I can't get it to work.
I follow the instructions here, yet I get the following error:
ERROR in ./src/index2.js
Module not found: Error: Can't resolve 'main.css' in C:\Users\magnusga\Downloads\Programming\TestPrograms\test\src'
# ./src/index2.js 1:0-27
# multi (webpack)-dev-server/client?http://localhost:8080 ./src/index2.js
I know for certain that main.css is in the same folder as index2.js
My Settings
index2.js
import css from 'main.css';
// ...much more code
webpack.config.js
module.exports = {
entry: {
app: './src/index2.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader']
}
],
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Development',
template: 'src/index.html',
inject: 'head'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index2.js",
"dependencies": {
"rxjs": "^5.5.6"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^2.30.1",
"postcss-loader": "^2.1.3",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"buildb": "babel src --watch --out-dir built --copy-files",
"watch": "webpack --watch",
"start": "webpack-dev-server",
"build": "webpack"
},
"author": "",
"license": "ISC"
}
One Fix
One fix is to use import css from './main.css'; instead of import css from 'main.css'; (note the ./ infront of the file name).
That does not feel right though, because the css-loader site shows that it should be the latter, not the former.
Is it a typo in the docs?
Thank you.
It is not really a typo. If you import it like this:
import css from 'main.css';
Webpack thinks, that you want to import a module, and searches for this file under node_modules. This is necessary, when you for example installed the bootstrap package and want to import its css. So when your css file comes from a dependency, you import that dependency like this. But when you want to import a lokal file, always use relative paths.
So it must be: import css from './main.css';
Further Reading:
https://webpack.js.org/concepts/module-resolution/#module-paths
https://webpack.js.org/configuration/resolve/#resolve-modules

Can't resolve "app.js" - Webpack

Problem
So, i'm working a web app using Webpack and ES6. When I try to run Webpack, it tells me that it can't resolve "app.js". I've looked all across the internet for a solution, but I just couldn't find one, can someone help me?
The Full error is:
ERROR in ./assets/js/main.js
Module not found: Error: Can't resolve 'app.js' in 'C:\Users\sidna\Dropbox\Dev Stuff\Web Apps\Mondrian Generator\assets\js'
# ./assets/js/main.js 4:0-17
webpack.config.js
module.exports = {
entry: './assets/js/main.js',
output: {
filename: 'assets/js/build.js',
},
watch: true,
module: {
loaders: [
{
test: /\.scss$/, loader: "style-loader!css-loader!sass-loader"
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
],
}
};
app.js (Empty)
main.js
// SCRIPTS
require("app.js");
// STYLES
require("../css/large.scss");
package.json
{
"name": "mondrian-generator",
"version": "1.0.0",
"description": "Create your own Mondrian",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"dependencies": {
"css-loader": "^0.28.0",
"style-loader": "^0.16.1",
"webpack": "^2.4.1"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-preset-env": "^1.4.0",
"node-sass": "^4.5.2",
"sass-loader": "^6.0.3",
"script-loader": "^0.7.0",
"webpack": "^2.4.1"
}
}
When the import is neither an absolute path (starting with /) nor explicitly a relative path (starting with ./ or ../), it is resolved as a module, which means it's Loading from node_modules Folders.
Your app.js is not in node_modules, so you need to change it to a relative path (assuming it's in the same directory as main.js):
require("./app.js");
Webpack follows the import behaviour of Node.js, but it also allows you to change it with the resolve.modules option.

Categories

Resources