I'm currently working on a react webpack babel etc site and trying to build the first time. The build is successful, but when I open up the browser I get the following error:
Uncaught Error: Cannot find module "/Users/michael.nakayama/Documents/Development/jamsesh/node_modules/webpack/node_modules/node-libs-browser/node_modules/process/browser.js"
This module exists. Going to that actual url in my browser shows the file in question. But I cannot figure out why webpack cannot find it. I don't know if this is a babel6 issue or a webpack issue, or neither. My config file looks like this:
var webpack = require('webpack');
var cleanWebpack = require('clean-webpack-plugin');
var ignore = new webpack.IgnorePlugin(new RegExp("/(node_modules|ckeditor)/"))
module.exports = {
devtool: 'inline-source-map',
entry: './lib/client/entry',
output: {
path: __dirname + '/public/js',
filename: 'app.js',
publicPath: 'http://localhost:8081/js/',
},
plugins: [
ignore,
],
resolve: {
extensions: ['', '.js'],
moduleDirectories: ['./node_modules']
},
module: {
loaders: [
{
test: /\.js?$/,
loaders: ['babel-loader?presets[]=react,presets[]=es2015,plugins[]=transform-es2015-classes,plugins[]=transform-react-jsx'],
exclude: /(node_modules)/,
}
]
}
}
and my webpack server file is as follows:
var WebpackDevServer = require('webpack-dev-server');
var webpack = require('webpack');
var config = require('../../webpack.config');
var server = new WebpackDevServer(webpack(config), {
// webpack-dev-server options
publicPath: config.output.publicPath,
stats: { colors: true },
});
server.listen(8081, 'localhost', function() {});
and here are the packages I have installed:
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.26",
"babel-loader": "^6.2.0",
"babel-plugin-syntax-jsx": "^6.3.13",
"babel-plugin-transform-es2015-classes": "^6.4.0",
"babel-plugin-transform-react-jsx": "^6.3.13",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"body-parser": "^1.14.2",
"clean-webpack-plugin": "^0.1.5",
"express": "^4.13.3",
"history": "^1.17.0",
"jade": "^1.11.0",
"nodemon": "^1.8.1",
"path": "^0.12.7",
"pg": "^4.4.3",
"react": "^0.14.6",
"react-dom": "^0.14.3",
"react-hot-loader": "^1.3.0",
"react-router": "^1.0.3",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
}
entry.js:
var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var routes = require('../routes');
// -v x.13.x
/**Router.run(routes, Router.HistoryLocation, function (Handler, state) {
React.render(<Handler/>, document.getElementById('react-app'));
});**/
var node = document.getElementById('react-app');
// -v 1.0.0
ReactDOM.render(<Router history={createBrowserHistory()} routes={routes}/> , node);
Also as a heads up, I have tried uninstalling and reinstalling all my packages. I have tried installing specifically the node-libs-browser modules. thanks.
The problem with ignore plugin on node_modules. In webpack.config.js, you have:
var ignore = new webpack.IgnorePlugin(new RegExp("/(node_modules|ckeditor)/"))
...
plugins: [
ignore,
],
From Ignore Plugin documentation:
Don’t generate modules for requests matching the provided RegExp.
Webpack tries to require module with the name node_modules/process/browser for React module and fails with it because it is ignored.
Try to remove node_modules from Ignore Plugin or write less global condition if you really need this.
Importing nodeExternals worked for me.
import nodeExternals from 'webpack-node-externals';
this is my server.webpack.config:
import path from 'path';
import nodeExternals from 'webpack-node-externals'; // changes
const CONTEXT = path.join( __dirname, "../.." ),
INPUT_SERVER_DIR = path.join( CONTEXT, "server" ),
OUTPUT_SERVER_DIR = path.join( CONTEXT, "dist/server" );
export default [
{
name: 'server',
target: 'node',
context: INPUT_SERVER_DIR,
node: {
__dirname: false
},
entry: './server',
devtool : 'source-map',
output: {
path: OUTPUT_SERVER_DIR,
filename: "server.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
resolve: {
extensions: ['.js']
},
**externals : [ nodeExternals() ]**
}
];
Related
I'm trying to use Tailwind v2 into an old project that uses .tpl files. Not an issue as we're migrating to the world of SPAs. What I'm doing should work regardless.
I'm using the following (literally taken from my package.json):
"autoprefixer": "^10.2.5",
"babel-loader": "^8.1.0",
"css-loader": "^5.0.0",
"mini-css-extract-plugin": "^1.5.0",
"extract-text-webpack-plugin": "^3.0.2",
"postcss-loader": "^5.2.0",
"postcss-preset-env": "^6.7.0",
"webpack-merge": "^5.7.3"
"postcss": "^8.2.12",
"sass": "^1.27.0",
"sass-loader": "^10.0.3",
"style-loader": "^2.0.0",
"tailwindcss": "^2.1.1",
"webpack": "^5.35.0",
"webpack-cli": "^4.6.0"
webpack-merge is solely used to distinguish file names for production and development.
Here's an exact copy of my webpack.config.js:
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const { SRC, DIST, ASSETS } = require('./paths')
module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'styles.css',
chunkFilename: '[id].css',
}),
new ExtractTextPlugin('styles.css', {
disable: process.env.NODE_ENV === 'development',
}),
],
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.s[ac]ss$/i,
use: ExtractTextPlugin.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}, {
loader: "postcss-loader"
}],
// use style-loader in development
fallback: "style-loader"
})
},
],
},
entry: {
scripts: path.resolve(SRC, 'js', 'index.js')
},
output: {
// Put all the bundled stuff in your dist folder
path: DIST,
// Our single entry point from above will be named "scripts.js"
filename: '[name].js',
// The output path as seen from the domain we're visiting in the browser
publicPath: ASSETS
},
}
After running the build command, I get:
TypeError: compiler.plugin is not a function
Removing new ExtractTextPlugin from the plugin, the error is gone but another error comes up stating it's needed. I've also looked at Tailwinds' example but not having any luck. I've also looked at the ExtractTextWebpackPlugin docs but.... no luck, same error.
This project uses *.scss, *.css, *.js, *.tpl, *.php
Appreciate the help or pointers.
Thanks.
This plugin has been DEPRECATED.
Please use: https://github.com/webpack-contrib/mini-css-extract-plugin
It's the first time i use webpack with babel, my goal is to make my small template app compatible with ie11.
For some reason I ignore, my JS does not work at all in ie11 even though I did set it as a target in my config. To test it, I use a ie11 on the internet but I don't have access to the stack errors since I'm on MacOS.
What am I missing here?
Source code for more info : https://github.com/VelynnXV/Front-End-Workflow
website : https://nifty-noether-cafbd5.netlify.app/
app.js
import regeneratorRuntime from "regenerator-runtime";
async function app() {
console.log('App entry point')
const template = document.getElementById('app')
await new Promise(r => setTimeout(() => r(), 2500))
template.innerHTML = `
<div class="web-container">
<div id="">
Async / awat test
</div>
</div>
`
console.log('App finished')
};
app();
webpack.config.json
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: ['core-js/stable', './src/app.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'app.js',
},
devServer: {
publicPath: "./src/",
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
},
plugins: [
new HtmlWebpackPlugin({ // will generate the html file WITH app.js
// see plugin here : https://webpack.js.org/plugins/html-webpack-plugin/
template: './src/index.html',
filename: './index.html'
})
],
module: {
rules: [ // set of rules letting webpack know how to handle .xyz files
{
test: /\.m?js$/, // source: https://webpack.js.org/loaders/babel-loader/
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
}
],
},
};
babel.config.js
// babel.config.js
module.exports = api => {
return {
plugins: [
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-transform-runtime",
],
presets: [
[
"#babel/preset-env",
{
useBuiltIns: "entry",
corejs:3,
// caller.target will be the same as the target option from webpack
targets: api.caller(caller => caller && caller.target === "node")
? { node: "current" }
: { chrome: "58", ie: "11" }
}
]
]
}
}
package.json
{
"name": "front-end-workflow",
"version": "1.0.0",
"description": "",
"main": "src/app.js",
"scripts": {
"dev": "npm run clean && npm run build && webpack serve",
"build": "webpack",
"clean": "rimraf ./dist"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.17",
"#babel/plugin-transform-runtime": "^7.12.17",
"#babel/preset-env": "^7.12.17",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^2.1.0",
"html-webpack-plugin": "^5.2.0",
"sass": "^1.32.8",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.23.0",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"#babel/runtime": "^7.6.3",
"core-js": "^3.3.2"
}
}
You almost have a complete configuration for IE11 support. The only thing you're missing is a target: "es5" option in your webpack configuration. Babel correctly transpiled your files. Webpack also injected all the necessary polyfills. However, you need to tell Webpack when it bundles the code together to use a syntax that your target browser can understand. For whatever reason, Webpack set the default to a version of ES that contained arrow functions. The error that IE11 console was showing (SCRIPT1002:syntax error) was pointing at the very first occurrence of an arrow function in your bundled app.js file.
An extra tip: use comments: false in your babel config to strip the code comments out of your bundle. This can slightly decrease the size of your bundle.
You can git apply this diff in your repo to take the changes in.
diff --git a/babel.config.js b/babel.config.js
index 8d2442b..273176c 100644
--- a/babel.config.js
+++ b/babel.config.js
## -2,6 +2,7 ##
module.exports = api => {
return {
+ comments: false,
plugins: [
"#babel/plugin-transform-runtime",
],
diff --git a/webpack.config.js b/webpack.config.js
index 2243a11..08af521 100644
--- a/webpack.config.js
+++ b/webpack.config.js
## -21,6 +21,7 ## module.exports = {
filename: './index.html'
})
],
+ target: "es5",
module: {
rules: [ // set of rules letting webpack know how to handle .xyz files using loader
// see loaders : https://webpack.js.org/loaders/
I make some tests to handle files located outside the webpack folder.
I have three simple files:
/*entry.js*/
import style from "./style.css";
import string from "./content.js";
console.log(string);
/*style.css*/
body {
background: beige;
}
/*content.js*/
export default string = "It works from content.js.";
I use ES6 syntax so I have a .babelrc like this:
{
"presets": [
"react",
"es2015"
]
}
Here is my webpack.config.js:
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: './../outsidefolder/client/wptest/entry.js',
//entry: './entry.js',
debug:true,
devtool:'source-map',
resolve: {
extensions: ['', '.js', '.jsx', '.css']
},
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js?$/,
loaders: ['babel']
},{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
}
]
},
plugins: [
new ExtractTextPlugin("app.css",{
allChunks: true
})
]
};
And my package.json
{
"private": true,
"devDependencies": {
"babel": "^6.3.26",
"babel-core": ">=5.8.29",
"babel-loader": ">=5.3.2",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"browser-sync": "^2.9.11",
"css-loader": "^0.21.0",
"extract-text-webpack-plugin": "^0.8.2",
"react-hot-loader": "^1.3.0",
"style-loader": "^0.13.0",
"webpack": "^1.12.2",
"webpack-dev-middleware": "^1.2.0",
"webpack-dev-server": "^1.12.1",
"webpack-hot-middleware": "^2.4.1",
"write-file-webpack-plugin": "^1.0.0"
}
}
When my entry is entry: './entry.js' all works well.
But when my entry point to an outside folder entry: './../outsidefolder/client/wptest/entry.js',
all goes wrong and I have this error:
ERROR in ../oustsidefolder/client/wptest/entry.js
Module parse failed: /Users/vikti/dev/webpacktut/node_modules/babel-loader/index.js!/Users/vikti/dev/oustsidefolder/client/wptest/entry.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import style from "./style.css";
| import string from "./content.js";
|
Is is possible to handle files with webpack outside the root folder?
Use path.join() and dirname to create an absolute path to the entry file.
webpack.config.js
var path = require('path');
//...
entry: path.join(__dirname, './../outsidefolder/client/wptest/entry.js'),
//...
I am having difficulty in getting CSS loading using css-loader on my JSX files. I was following the example from:
https://christianalfoni.github.io/react-webpack-cookbook/Loading-CSS.html
This is my JSX
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './styles.css';
class Hello extends React.Component {
render() {
return <div>Hello world!</div>
}
}
var el = document.getElementById('content')
var data = JSON.parse(el.getAttribute('data-attr'))
ReactDOM.render(<Hello data={data} />, el);`
This is my package.json
"devDependencies": {
"babel-core": "^6.3.26",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"css-loader": "^0.23.1",
"exports-loader": "~0.6.2",
"expose-loader": "~0.6.0",
"grunt": "^0.4.5",
"grunt-babel": "^6.0.0",
"grunt-cli": "^0.1.13",
"grunt-contrib-watch": "^0.6.1",
"grunt-webpack": "^1.0.11",
"history": "^1.17.0",
"imports-loader": "~0.6.3",
"jquery": "^2.1.4",
"lodash": "~3.0.0",
"react": "^0.14.5",
"react-dom": "^0.14.5",
"react-router": "^1.0.3",
"style-loader": "^0.13.0",
"webpack": "^1.12.9",
"webpack-dev-server": "^1.14.0"
},
"dependencies": {
"chunk-manifest-webpack-plugin": "0.0.1",
"grunt-react": "^0.12.3"
}
This is my Webpack.config.js
var path = require('path');
var webpack = require('webpack');
var config = module.exports = {
// the base path which will be used to resolve entry points
context: __dirname,
// the main entry point for our application's frontend JS
entry: './app/frontend/javascripts/entry.js',
stats: {
// Configure the console output
colors: true,
modules: true,
reasons: true
},
progress: true,
keepalive: true,
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader', // 'babel-loader' is also a legal name to reference
query: { presets: ['es2015', 'react'] }
},
{ test: /\.css$/, loader: "style-loader!css-loader" }
]
},
output: {
// this is our app/assets/javascripts directory, which is part of the Sprockets pipeline
path: path.join(__dirname, 'app', 'assets', 'javascripts'),
// the filename of the compiled bundle, e.g. app/assets/javascripts/bundle.js
filename: 'bundle.js',
// if the webpack code-splitting feature is enabled, this is the path it'll use to download bundles
publicPath: '/assets',
devtoolModuleFilenameTemplate: '[resourcePath]',
devtoolFallbackModuleFilenameTemplate: '[resourcePath]?[hash]',
},
resolve: {
// tell webpack which extensions to auto search when it resolves modules. With this,
// you'll be able to do `require('./utils')` instead of `require('./utils.js')`
extensions: ['', '.js'],
// by default, webpack will search in `web_modules` and `node_modules`. Because we're using
// Bower, we want it to look in there too
modulesDirectories: [ 'node_modules', 'bower_components' ],
},
plugins: [
// we need this plugin to teach webpack how to find module entry points for bower files,
// as these may not have a package.json file
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('.bower.json', ['main'])
]),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
//new webpack.optimize.CommonsChunkPlugin('common-bundle.js'),
//new webpack.optimize.CommonsChunkPlugin('public-bundle.js')
]
};
This is my styles.css
#div {
background-color: red;
}
The output I get from running my grunt task to run 'webpack' attached:
You can see where it says the build failed for the CSS.
cjs require fbjs/lib/mapObject [154] ./~/react/lib/ReactDOMFactories.js 18:16-45
[157] ./~/react/lib/onlyChild.js 1.21 kB {0} [built]
cjs require ./onlyChild [153] ./~/react/lib/ReactIsomorphic.js 24:16-38
[158] ./~/react/lib/deprecated.js 1.77 kB {0} [built]
cjs require ./deprecated [3] ./~/react/lib/React.js 19:17-40
[159] ./~/react-dom/index.js 63 bytes {0} [built]
cjs require react-dom [0] ./app/frontend/javascripts/entry.js 11:16-36
ERROR in ./app/frontend/javascripts/styles.css
Module parse failed: /Users/Booboo/Projects/Xeon/app/frontend/javascripts/styles.css Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.
| div {
| background-color: red;
| }
# ./app/frontend/javascripts/entry.js 5:0-23
Warning: Task "webpack:dev" failed. Use --force to continue.
Aborted due to warnings.
Booboo$ grunt react && grunt webpack && grunt watch
I encounter this problem too.
But in my case, I found my loader was written as
{test: '/\.css$/', loader: 'style!css'}
which should be correctly written as
{test: /\.css$/, loader: 'style!css'}
note the '' around the /.css$/
I wise this would be helpful for you.
When you say
import styles from './styles.css';
you're trying to import a module that's not being exported as a module.
Try
import './styles.css';
instead to make it a simple file import.
I have been using react since a while now and wanted to try it with webpack.
Here is my webpack.config.js :
var path = require('path');
module.exports = {
entry: './app.js',
output: {
path: path.resolve(__dirname, "build"),
publicPath: "/",
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
},
resolve: {
extensions: ['', 'js', 'jsx']
}
}
The error that occurs is as follows :
ERROR in ./~/react/react.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./lib/React in /Users/username/path/to/app/node_modules/react
# ./~/react/react.js 3:17-39
This error is occurring when I am importing react into my file by using either var React = require('react') or import React from 'react';
I have the required preset packages for babel installed :
"devDependencies": {
"babel-core": "^6.4.0",
"babel-loader": "^6.2.1",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"webpack": "^1.12.10",
"webpack-dev-server": "^1.14.0"
},
"dependencies": {
"highcharts-release": "^4.2.1",
"immutable": "^3.7.6",
"react": "^0.14.5",
"react-highcharts": "^6.0.0",
"react-redux": "^4.0.6",
"redux": "^3.0.5"
}
Thanks!
Based on your pastebin example, you can see that webpack is looking for React, Reactjs, or Reactjsx, not React.js:
/Users/bIgB/Private/Code/go-projects/src/github.com/bIgBV/cereberus/app/node_modules/react/lib/React doesn't exist
/Users/bIgB/Private/Code/go-projects/src/github.com/bIgBV/cereberus/app/node_modules/react/lib/Reactjs doesn't exist
/Users/bIgB/Private/Code/go-projects/src/github.com/bIgBV/cereberus/app/node_modules/react/lib/Reactjsx doesn't exist
To fix this, simply add a . to the front of your extensions, like so:
resolve: {
extensions: ['', '.js', '.jsx']
}
https://webpack.github.io/docs/configuration.html#resolve-extensions