Webpack relative path resolve error - javascript

I'm importing a module like this import { validate } from '../../_lib';
but webpack throws me an error ModuleNotFoundError. Looking inside it seems like it parses the path in a wrong why: resolve file c:/Users/Me/project/resource/func\\_lib doesn't exist
My directory looks something like this:
project
resource
func
file.js
_lib
validate.js
index.js
in validate.js I'm exporting a func like this export function validate(){}
and in index.js I'm exporting validate this way export * from './validate'
this is mt webpack config
var webpack = require('webpack');
module.exports = {
// entry: provided by serverless
// output: provided by serverless
target: 'node',
externals: [
'aws-sdk',
'dynamodb-doc'
],
resolve: {
extensions: ['', '.js', '.jsx']
},
devtool: 'source-map',
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
unused: true,
dead_code: true,
warnings: false,
drop_debugger: true
}
}),
function () {
this.plugin("done", function (stats) {
if (stats.compilation.errors && stats.compilation.errors.length) {
console.error(stats.compilation.errors)
throw new Error(stats.compilation.errors);
}
});
}
],
module: {
loaders: [
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015', 'stage-0']
}
}
]
}
};

Related

Issue with integrating cortex-js/compute machine in react application

I am trying to use compute machine provided by the cortexjs. https://cortexjs.io/compute-engine
I saved this dependency using
npm i #cortex-js/compute-engine
After I ran npm start, I am getting this error:
ERROR in ./node_modules/#cortex-js/compute-engine/dist/compute-engine.min.js 2:1360
Module parse failed: Unexpected token (2:1360)
You may need an appropriate loader to handle this file type.
Following is my webpack file:
var webpack = require('webpack');
const HtmlWebPackPlugin = require("html-webpack-plugin");
var path = require('path');
module.exports = {
// output: {
// path: path.resolve(__dirname, 'dist'),
// filename: 'main.js',
// publicPath: '/'
// },
mode : 'production',
devServer: {
historyApiFallback: true,
},
devtool: "source-map",
module: {
rules: [
{
test: /\.(png|jpg|woff|woff2|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.css$/,
loader: 'style-loader'
},
{
test: /\.css$/,
loader: 'css-loader',
options: {
import: true,
},
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
Please can someone suggest which loader should I add to webpack.config file to make this work.

multiple errors auth0 react apollo babel webpack

I'm having a little bit of an issue when I want to implement auth0 on my project.
Whenever I solve one problem I run into another, it's always the same 3 errors :
-require is not a function
-window is not defined
-missing class properties
I've tried solving it by playing with the babelrc, changing the order of the presets
And in webpack I've added the famous as below:
"plugins: [new webpack.DefinePlugin({ 'global.GENTLY': false })],"
in webpack to no avail
I'm providing the package json/ babelrc & web pack without the modifications I cited above so you can see the "base" without the failed attempts at fixing it
Also providing the screenshots with the errors
Thanks in advance
https://imgur.com/a/8TT3v44
for the errors
this is in babelrc
{
"presets": [
"#babel/preset-react",
["#babel/preset-env", { "modules": false }],
["#babel/preset-stage-0", { "decoratorsLegacy": true }]
],
"env": {
"development": {
"compact": false
},
"jest": {
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
},
"plugins": [
"#babel/plugin-proposal-export-default-from",
[
"react-intl",
{
"messagesDir": "./extracted_messages/",
"enforceDescriptions": true
}
]
]
}
and this is the webpack
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const distDir = path.join(__dirname, '../dist')
const srcDir = path.join(__dirname, '../src')
module.exports = [
{
name: 'client',
target: 'web',
mode: 'development',
entry: `${srcDir}/client.jsx`,
output: {
path: distDir,
filename: 'client.js',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.join(__dirname, '../config'),
utils: path.join(__dirname, '../src/utils'),
toolbox: path.join(__dirname, '../src/components/toolbox')
}
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules\/)/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
query: { name: 'assets/images/[name].[ext]' }
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: 'file-loader',
query: { name: 'assets/fonts/[name].[ext]' }
}
]
},
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new MiniCssExtractPlugin({
filename: 'styles.css'
}),
new CopyPlugin([{ from: `${srcDir}/favicon.ico`, to: distDir }])]
},
{
name: 'server',
target: 'node',
mode: 'development',
entry: `${srcDir}/server.jsx`,
output: {
path: distDir,
filename: 'server.js',
libraryTarget: 'commonjs2',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
alias: {
config: path.join(__dirname, '../config'),
utils: path.join(__dirname, '../src/utils'),
toolbox: path.join(__dirname, '../src/components/toolbox'),
inherits: 'inherits/inherits_browser.js',
superagent: 'superagent/lib/client',
emitter: 'component-emitter',
}
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules\/)/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
{
loader: 'isomorphic-style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
query: { name: 'assets/images/[name].[ext]' }
},
{
test: /\.(woff2?|eot|ttf|otf)$/,
loader: 'file-loader',
query: { name: 'assets/fonts/[name].[ext]' }
}
]
},
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new CopyPlugin([{ from: `${srcDir}/favicon.ico`, to: distDir }])]
}
]
I ran into this problem while writing for our blog. Our suggested fix is this;
function whatYouRunOnPageLoad() {
if (typeof window !== undefined) {
auth0.parseHash(... etc ...)
}
}
parseHash requires window, which does not exist as part of your render steps. Auth0.js cannot run from serverside, which is what is "accidentally" happening when you try to render it the way you are.
Window error solved by doing:
if(global.window){...}
and later on by just not calling the function I was using at inappropriate times.
Require is not a function solved with:
[new webpack.DefinePlugin({ 'global.GENTLY': false })]
in the webpack config at plugins (dev AND prod, idk why) + importing it with require and not import.
Webpack module error solved by changing the order of the presets in bablerc.

SCSS sourcemaps not working with Webpack 3 + ExtractTextPlugin

I'm trying to enable sourcemaps for my SCSS in my app and have a really puzzling situation on my hands. Here's my config file:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssets = require('optimize-css-assets-webpack-plugin');
let config = {
entry: './src/index.ts',
devtool: 'eval-source-map', // for choosing a style of source map
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist')
},
devServer: {
contentBase: path.resolve(__dirname, './dist'), // A directory or URL to serve HTML content from
historyApiFallback: true, // fallback to /index.html for SPA
inline: true,
open: false // open default browser on launch
},
module: {
rules: [
{
test: /\.ts$/, // files ending with .ts
exclude: /node_modules/, // exclude the node modules directory
use: 'ts-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["env"]
}
}
},
{
test: /\.scss$/, // files ending with .scss
use: ['css-hot-loader'].concat(
ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
// { loader: 'style-loader', options: { sourceMap: true } },
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
],
})
)
},
{
test: /\.(png|svg|jpg|gif)$/, // for other file types
use: ['file-loader?name=[name].[ext]&outputPath=img/']
}
]
},
resolve: {
extensions: ['.ts', '.js']
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new ExtractTextPlugin('styles.css') // call the ExtractTextPlugin and name our CSS file
]
};
module.exports = config;
if (process.env.NODE_ENV === 'production') {
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin(), // call the uglify plugin
new OptimizeCSSAssets() // call the CSS optimizer (for minification)
);
}
What's really strange is that here, everything in the terminal compiles fine but when I inspect an element, there's no sourcemap:
HOWEVER, if uncomment this line in my webpack.config file:
// { loader: 'style-loader', options: { sourceMap: true } },
and run npm start again, the sourcemaps work correctly!...
...but now the terminal throws an error, which apparently is because you aren't supposed to use style-loader inside of the ExtractTextPlugin, but rather only as a fallback. My app still works in this case, but I don't want that error! How can I enable the SCSS sourcemaps without including style-loader in my SCSS rules?

How to uglify javascript using webpack

Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
var CompressionPlugin = require("compression-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: './index.js',
output: {
path: __dirname,
filename: 'public_html/assets/js/bundle.js'
},
resolveLoader: {
modules: ["node_modules"]
},
module: {
rules: [
{
enforce: 'pre',
test: /\.tag$/,
exclude: /node_modules/,
loader: 'riotjs-loader',
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [
'es2015',
],
"babelrc": false
}
},
{
test: /\.css$/,
use: [
{
loader: "css-loader",
options: {
modules: false
}
}
]
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({debug: true}),
new UglifyJSPlugin(),
new webpack.ProvidePlugin({
riot: 'riot'
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.(js|html)$/,
threshold: 10240,
minRatio: 0.8
})
]
}
This completely uglifies the bundle js but the problem is global variables references are lost. I mean the properties of global object DataMixin are lost.
For example, inside index.html I have:
<script>
window.onload = function () {
DataMixin.get_data_page_load(); //DataMixin defined in other js file
};
</script>
After uglifying, I get error:
Cannot read property 'get_data_page_load' of undefined
How do I fix this? I am using webpack 2.
For webpack 2 you don't need to install the external uglify plugin.
In your webpack config replace this new UglifyJSPlugin(), with the following:
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compressor: {
warnings: false,
},
}),
Removing presets fixed it but also had to remove arrow functions from my code.
Here is the solution I found: http://www.rootscopeblog.com/blog/post?=uglifying-riotjs-files-using-webpack-2

Module not found: Error: Cannot resolve module 'module'

I want to load module from variable string
var abc = './../containers/BlankContainer';
require(abc);
but it cannot find module, so I install 'require-from-string' module from npm.
Now when I build it's giving error
ERROR in ./~/require-from-string/index.js
Module not found: Error: Cannot resolve module 'module' in D:\Nilay\RnD\node_modules\require-from-string
# ./~/require-from-string/index.js 3:13-30
I found it is webpack issue, here is my webpack config:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin')
var entry = [path.resolve(__dirname, 'app/bootstrap.js')];
var output = {
path: path.resolve(__dirname, 'public/dist'),
filename: 'bundle-[name].js',
publicPath: "dist/"
};
var modules = {
loaders: [
{ test: /\.json$/, loader: "json-loader" },
{ test: /\.js$/,
loader: ['babel-loader'], exclude: /node_modules/, query: { cacheDirectory: 'babel_cache', presets: ['react', 'es2015'] } },
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader") },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.(woff|woff2)$/, loader: "file-loader" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" }
]
};
var plugins = [
new ExtractTextPlugin("bundle.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ // minimize/compress all js chunks
compress: { warnings: false },
mangle: false,
sourcemap: false,
beautify: false,
dead_code: true
})
]
module.exports = {
entry: entry,
output: output,
stats: { colors: true },
watch: true,
module: modules,
plugins: plugins,
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
resolve: {
modules: [path.resolve(__dirname, '/app/routes'), 'node_modules/'],
descriptionFiles: ['package.json'],
extensions: ['', '.js', '.ts']
}
};
How can I resolve it?

Categories