webpack config doesn't work with require() in node.js - javascript

I have a file call abc.jsx like this
var MyTitle = require('./MyTitle')
but I have to do require('./MyTitle)
coz I run webpack it throw me error.
ERROR in ./js/MyTitle.jsx
Module not found: Error: Cannot resolve 'file' or 'directory' ./MyTitle in /Users/username/Documents/intro-to-react/js
# ./js/MyTitle.jsx 5:14-34

You should have set webpack config to resolve jsx file using babel-loader. The following line test: /\.js?$/, in module loader tells webpack to resolve both .js and .jsx file types.
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: "inline-sourcemap",
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
}
};

Related

Webpack can't resolve relative path import express static

I'm working on an outlook addin I have an express server running. I am setting webpack because I need to transpile js to es5 to make it work in Outlook Desktop. Here is the simplified project structure.
/public
/javascripts
ssoAuth.js
/addin
/commmands
commands.js
commands.html
/server
/bin
/helpers
app.js
The public folder is set as a static folder in my express server
app.use(express.static(path.join(__dirname, '../public'),
My problem is in commands.js I import ssoAuth.js with es6 module import with relative path :
import getGraphAccessToken from "/javascripts/ssoAuthES6.js";
It works fine when I run node ./server/app.js and load my outlook addin, but when I want to use Webpack to bundle, the import is not working, I get :
ERROR in ./addin/commands/commands.js
Module not found: Error: Can't resolve '/javascripts/ssoAuth.js'
I can't figure out how to configure webpack to allow the imports from the public folder.
Here are my webpack config files :
webpack.config.js :
const config = {
devtool: "source-map",
entry: {
polyfill: "#babel/polyfill",
commands: "./addin/commands/commands.js"
},
resolve: {
extensions: [".ts", ".tsx", ".html", ".js"]
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.html$/,
exclude: /node_modules/,
use: "html-loader"
},
{
test: /\.(png|jpg|jpeg|gif)$/,
use: "file-loader"
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
filename: "commands.html",
template: "./addin/commands/commands.html",
chunks: ["polyfill", "commands"]
})
]};
webpack.server.config.js :
return ({
entry: {
server: './server/bin/www',
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new CopyWebpackPlugin([
{
to: "./public",
from: "./public"
}
])
]})
Can you help figure this out ? Is there a better folder structure that I should use to make it work ?
Thanks
You're using an absolute path
import getGraphAccessToken from "/javascripts/ssoAuthES6.js";
// ^ this will look in your topmost directory on your OS
The relative path, from commands.js, would be:
import getGraphAccessToken from "../../javascripts/ssoAuthES6.js";
Alternatively, you can set Webpack to look for modules from your root directory by adding the following to your webpack configuration:
{
// ...
resolve: {
modules: [path.resolve(__dirname, "src"), "node_modules"],
},
// ...
}
Then you can import from your project's root directory from anywhere, like so:
import getGraphAccessToken from "javascripts/ssoAuthES6.js";
Some other points:
Since you're setting the extensions: [".ts", ".tsx", ".html", ".js"], you don't need to provide file extensions for those imports
You specify .ts and .tsx in your webpack config, but you are using .js files. Consider removing the Typescript extensions
If you are using Typescript, you will need to update import paths in your tsconfig.json
You can consider import path aliases in both Webpack and Typescript to be more explicit that your imports are coming from your project root. Instructions here

Error in React: unknown word when using webpack

I have set up a React environment with webpack and babel. However, when I run webpack-dev-server --progress --colors, I get error like this:
ERROR in multi (webpack)-dev-server/client?http://localhost:8080 E:/src/index.js
Module not found: Error: can't resolve 'E:\src/index.js' in 'E:\personal_projects\web-site-name'
...
(2:1) Unknown word
1: var url = require("url");
^
My webpack.config.js file is this:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, '/public');
var APP_DIR = path.resolve(__dirname, '/src');
var config = {
entry: APP_DIR + '/index.js',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /(\.css$)/,
loaders: ['style-loader', 'css-loader', 'postcss-loader']
},
{
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}
}
]
}
};
module.exports = config;
I think there is some problem with babel and it compiling my index.js to my bundle.js file. Any advice on this?
You either need to use path.join or remove your slashes, e.g.
path.resolve(__dirname, '/src');
and other lines using resolve should be
path.resolve(__dirname, 'src');
or
path.join(__dirname, 'src');
or even
path.join(__dirname, '/src');
Your usage of .resolve passes an absolute path /src, meaning that the first argument is essentially discarded.

Uncaught ReferenceError: require is not defined react + webpack

I have been working on a project for about 2 months and used webpack-dev-middleware.
According to the WDM documentation, its just a wrapper for webpack and run the project in the memory to enable hot reloading.
But now when im trying to build and deploy with webpack and same webpack.config.js i get Uncaught ReferenceError: require is not defined error.
I have searched alot and couldn't find a right answer for my case.
I'd really appreciate any help :).
my webpack.config.js
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var autoprefixer = require('autoprefixer');
const webpack = require('webpack');
var fs = require('fs')
module.exports = {
entry: './src/client.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
target: 'web',
// keep node_module paths out of the bundle
externals: fs.readdirSync(path.resolve(__dirname, 'node_modules')).concat([
'react-dom/server', 'react/addons',
]).reduce(function (ext, mod) {
ext[mod] = 'commonjs ' + mod
return ext
}, {}),
node: {
__filename: true,
__dirname: true
},
plugins: [
new ExtractTextPlugin('styles.css'),
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
}, {
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=100000&name=/[hash].[ext]',
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader']),
},
{ test: /\.json$/, loader: "json-loader"}
],
},
devtool: 'cheap-module-source-map'
}
I'm using webpack version : 1.13.3 as local.
In my case reason was:
...
module: {
noParse: /\.min\.js$/,
...
I've commented it out

Possible to have separate src from modules and webpack config?

I have an app that is in a different folder structure than the modules installed from the package.json and I cannot find a way to make it work:
Structure:
includes
build
build stuff
src
shared assets
js
...APP (the app is a few folders down still)
How can I specify that the modules are somewhere and the app is in another place? Is this even possible? as If I set up the src of my app in the place where the build setup is, everything work as expected.
Where is my very simple webpack config.
var getters = require('./../gulpfile.js/config/getters');
var path = require('path');
var appRoot = path.resolve(__dirname, '../src');
var appRoot2 = path.resolve(__dirname, '../../main/jcr_root/etc/designs/fit/includes/shared_assets/js/vueapps/chat_app/src');
module.exports = {
context: appRoot2,
entry: './main.js',
output: {
filename: 'app.js',
path: getters.js.vue.apps.chatapp.dist
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader',
exclude: /node_modules/
},
{
test: /\.js$/,
loaders: 'babel-loader',
exclude: /node_modules/
}
]
},
resolve: {
modules: [
'node_modules'
]
}
};
I this you can see I have appRoot and appRoot2, appRoot works as expected, appRoot2 fails giving me this error.
ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in ...
EDIT: Forgot to mention I'm using :
"vue-loader": "^9.4.0".
"webpack": "^2.2.0".
"babel-loader": "^6.3.2".
EDIT2: Got it working, had to specify with another option:
resolveLoader: {
modules: [
nodeRoot
],
}
Also in the loader had to add this option:
{
test: /\.js$/,
loaders: 'babel',
exclude: /node_modules/,
query: {
presets: [nodeRoot + '/babel-preset-es2015'],
}
}
With the path to the preset.

Cannot import ES6 module inside React component

I have a config file named config.js that looks like this :
var config = {};
config.web = {};
config.web.param = 'oneParam';
module.exports = config;
I also use Webpack to give alias to my modules so I have this line in my webpack.config.js :
alias: {
configFile: 'app/config.js'
}
I then try to import my config file with this :
import config from 'configFile';
Inside a React Component.
However, when I try to access configvariable, all I get is an undefined error.
My full webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: [
'./app/app.jsx'
],
output: {
path: __dirname,
filename: './dist/bundle.js'
},
externals: {
'Config': JSON.stringify()
},
resolve: {
root: __dirname,
alias: {
configFile: 'app/config.js'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
},
{test: /\.scss?$/, exclude: /node_modules/, loader: "style-loader!css-loader!sass-loader!"},
{test: /\.css?$/, loader: "style-loader!css-loader!"},
{test: /\.(png|jpg)$/, loader: "file-loader?name=./dist/images/[name].[ext]"}
]
},
devtool: 'cheap-module-source-map'
};
What am I doing wrong here ?
Try
import * as config from 'configFile';
And try console.log the config variable and see if you get not defined. If it is still not defined, the problem lies in exporting the configFile.
Your path 'app/config.js' will the most probably point to node_modules/app/config.js.
The simplest solution will be changing your path in alias to absolute (or more proper in your scenario):
alias: {
configFile: '/app/config.js'
}
You should define relative path to root:
alias: {
configFile: './app/config.js'
}
or relative to contentBase

Categories