Webpack JSX cannot resolve relative module through ES6 imports - javascript

I'm setting up webpack for a large already existing React App.
Seems to be working fine but some modules causes trouble unless I specifically add the extension to the import
//not working
import AppRouter from './router';
//working but meh
import AppRouter from './router.jsx';
It does not occur in all the relative imports but some for what I see look random.
The error, it occur multiple times for different files
ERROR in ./src/main/resources/js/cs/index.js
Module not found: Error: Can't resolve './router' in '<ommited_path>/src/main/resources/js/cs'
# ./src/main/resources/js/cs/index.js
The folder structure for that file
/src
--/main
--/resources
--/js/
--/cs
index.js
router.jsx
store.js
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const paths = require('./config/paths');
const config = {
entry: {
index: path.join(__dirname, paths.custServReactIndex),
},
output: {
path: path.join(__dirname, paths.outputScriptsFolder),
filename: '[name].js',
publicPath: paths.outputScriptsFolder,
},
mode: 'development',
module: {
rules: [
{
// Compile main index
test: /\.jsx?$/,
loader: 'babel-loader',
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
module.exports = config;
.babelrc
{
"ignore": ["node_modules"],
"presets": ["env", "stage-0", "react"]
}
That being said, any idea on why some relative imports are failing and how can I solve so?

You need to add resolve extensions. Add the below config in Webpack and restart React app
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
}

Related

Disable Strict Mode in None Module Library

I want to bundle a JavaScript project by WebPack but there is more problems in none-module libraries because imported them by 'import' capability,ECMAScript 6 module loader run strict mode by default and it tack more errors.
Question :
How can I import none module libraries without strict mode to bundle them by WebPack?
index.js
import '../examples/js/libs/draco/draco_encoder.js';
import './js/libs/codemirror/codemirror.js';
import './js/libs/codemirror/mode/javascript.js';
import './js/libs/codemirror/mode/glsl.js';
...
webpack.config.js
const path = require('path');
const webpack = require('webpack');
// webpack.config.js
module.exports = {
entry: {
polyfills: './editor/polyfills',
index: './lib/index.js',
},
mode: 'development',
output: {
path: __dirname,
publicPath: '/',
filename: './editor/[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
watchContentBase: true,
publicPath: "/",
contentBase: "./",
hot: true,
port: 8080,
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
};
babel.config.json
{
"presets": [
"#babel/preset-env"
]
}
I tryed :
babel
esmify
browserify
Shimming in WebPack
...
Thanks for your attention.
Webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript.
About loaders: Loaders.
You can easily write your own loaders using Node.js : Writing Loader.
For execute JS script once in global context that can solved my problem : Script Loader

WebPack importing react custom packages in another folder

I am enhancing a website with ReactJS.
My folder structure looks something like this:
_npm
node_modules
package.json
package-lock.json
webpack.config.js
_resources
js
react
reactapp1.js
reactapp2.js
components
FormDisplay.js
I want to import a custom reactjs package into the FormDisplay component.
When I enter:
import PlacesAutocomplete from 'react-places-autocomplete'
This doesn't work. But if I enter:
import PlacesAutocomplete from "./../../../_npm/node_modules/react-places-autocomplete";
This works. I understand why this is the case. I was wondering if there was a way that I can just enter:
import PlacesAutocomplete from 'react-places-autocomplete';
How do I make it work with just that line of code, without having to find the path to node_modules folder?
My webpack config:
const path = require("path");
const webpack = require("webpack");
const PATHS = {
app: path.join(__dirname, "../_resources/react/"),
build: path.join(__dirname, '../wordpress_site/wp-content/themes/custom_theme/assets/js/'),
};
module.exports = {
entry: {
reactapp1: path.join(PATHS.app, "reactapp1.js"),
reactapp2: path.join(PATHS.app, "reactapp2.js")
},
output: {
filename: "[name].bundle.js",
//path: path.join(__dirname, "dist")
path: PATHS.build
},
module:{
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"],
plugins: ["transform-class-properties"]
}
}
}
]// rules array
}, // module
}
Have you tried using webpack's resolve-modules?
resolve: {
modules: ['_npm/node_modules']
}
Might work

Webpack - module not found even though module exists

This is a branch off of my previous question and applied suggestions. But I am still having major issues.
I now have my babel transpiler, along with a .babelrc file in place. My import code to import my module looks like this:
var init = require('./app/js/modules/toc');
init();
However I'm getting this:
ERROR in ./app/js/script.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./app/js/modules/toc in /projects/project-root/app/js
# ./app/js/script.js 1:11-42
Webpack config:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./app/js/script.js",
module: {
rules: [{
test: /\.js$/,
use: 'babel-loader'
}]
},
output: {
path: __dirname + "public/javascripts",
filename: "scripts.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
.babelrc
{
"presets": ["es2015"]
}
Gulptask
//scripts task, also "Uglifies" JS
gulp.task('scripts', function() {
gulp.src('app/js/script.js')
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('public/javascripts'))
.pipe(livereload());
});
I'm totally lost...what am I doing wrong?
For my import code I also tried:
import {toc} from './modules/toc'
toc();
UPDATE: As recommended I needed to add resolve to my config. It looks like this now:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: "./app/js/script.js",
resolve: {
extensions: ['.js']
},
module: {
rules: [{
test: /\.js$/,
use: 'babel-loader'
}]
},
output: {
path: __dirname + "public/javascripts",
filename: "scripts.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};
Sadly I still get:
ERROR in Entry module not found: Error: Cannot resolve 'file' or
'directory' ./app/js/script.js in /projects/project-root
Does my file structure need to change?
Whenever you import/require a module without specifying a file extension, you need to tell webpack how to resolve it. This is done by the resolve section inside the webpack config.
resolve: {
extensions: ['.js'] // add your other extensions here
}
As a rule of thumb: whenever webpack complains about not resolving a module, the answer probably lies in the resolve config.
Let me know about any further questions and if this works.
EDIT
resolve directly to the root level of your config:
// webpack.config.js
module.export = {
entry: '...',
// ...
resolve: {
extensions: ['.js']
}
// ...
};
You are specifying an entry point in your webpack config AND in gulp. Remove the entry property in your webpack config.
If you specify it twice, the gulp config will tell webpack to get the file in ./app/js/script.jsand then webpack in ./app/js/script.js which will result in a path like ./app/js/app/js/script.js.
Keep us posted if you fixed it. =)
Given that your script is located at ./app/js/script.js and the requested module is there ./app/js/modules/toc, you would need to call it relatively to your script => ./modules/toc should work.
This is because both your script and module are located in the jsfolder.

webpack: 'import' not working whereas 'require' works okay

I have a strange issue using webpack.
This my webpack.config.js:
import webpack from "webpack";
import path from "path";
//not working: import ExtractTextPlugin from "extract-text-webpack-plugin";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const GLOBALS = {
"process.env.NODE_ENV": JSON.stringify("production"),
__DEV__: false
};
export default {
debug: true,
devtool: "source-map",
noInfo: true,
entry: "./src/bootstrap",
target: "web",
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "bundle.js"
},
resolve: {
root: path.resolve(__dirname),
alias: {
"~": "src"
},
extensions: ["", ".js", ".jsx"]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin(GLOBALS),
new ExtractTextPlugin("styles.css"),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
],
module: {
loaders: [
{ test: /\.jsx?$/, include: path.join(__dirname, "src"), loaders: ["babel"] },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: "file" },
{ test: /\.(woff|woff2)$/, loader: "file-loader?prefix=font/&limit=5000" },
{ 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|\.scss)$/,
loader: ExtractTextPlugin.extract("css?sourceMap!sass?sourceMap")
}
]
}
};
As you can see: I set up an alias "~" pointing to my "src" directory.
According to webpack documentation I should be able to import modules this way:
import { ServiceStub } from "~/utilities/service-stub";
HINT: File service-stub.js sits here: [__dirname]/src/utilities/service-stub.js.
However, this does not work since webpack is throwing an error ("Path not found.").
When I userequire instead of import, everything works fine:
const { ServiceStub } = require("~/utilities/service-stub");
The same issue is in webpack.config.js itself:
import webpack from "webpack";
import path from "path";
//not working: import ExtractTextPlugin from "extract-text-webpack-plugin";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
Here some modules import well with import (modules webpack and path), some do not (module extract-text-webpack-plugin).
I worked through dozens of forums, but found no solution yet.
The problem is ESLint - not webpack.
When you are using aliases in webpack like this
resolve: {
root: path.resolve(__dirname),
alias: {
"~": "src"
},
extensions: ["", ".js", ".jsx"]
}
and you are importing this way
import { ServiceStub } from "~/services/service-stub";
ESLint cannot resolve the alias and reports an error.
To get it work you must tell ESLint to ignore some rule with "import/no-unresolved": 0. This seems to be okay because if an imported file is actually missing, webpack reports an error itself.

What is the best practice for importing angularjs using webpack?

How do you use Webpack and AngularJS together, and how about template loading and on demand fetching of resources?
An example of a well written webpack.config.js file for this purpose would be very much appreciated.
All code snippets displayed here can be accessed at this github repo. Code has been generously adapted from this packetloop git repo.
webpack.config.json
var path = require('path');
var ResolverPlugin = require("webpack/lib/ResolverPlugin");
var config = {
context: __dirname,
entry: ['webpack/hot/dev-server', './app/app.js'],
output: {
path: './build',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.css$/,
loader: "style!css-loader"
}, {
test: /\.scss$/,
loader: "style!css!sass?outputStyle=expanded"
}, {
test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/,
loader: "file"
}, {
test: /\.html$/,
loader: "ngtemplate?relativeTo=" + path.join(__dirname, 'app/') + "!raw"
}]
},
// Let webpack know where the module folders are for bower and node_modules
// This lets you write things like - require('bower/<plugin>') anywhere in your code base
resolve: {
modulesDirectories: ['node_modules', 'lib/bower_components'],
alias: {
'npm': __dirname + '/node_modules',
'vendor': __dirname + '/app/vendor/',
'bower': __dirname + '/lib/bower_components'
}
},
plugins: [
// This is to help webpack know that it has to load the js file in bower.json#main
new ResolverPlugin(
new ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
)
]
};
module.exports = config;
To import AngularJS into the main app.js you do the following:
app/vendor/angular.js
'use strict';
if (!global.window.angular) {
require('bower/angular/angular');
}
var angular = global.window.angular;
module.exports = angular;
And then use it in app.js like so,
app.js
...
var angular = require('vendor/angular');
// Declare app level module
var app = angular.module('myApp', []);
...
Is the following correct? Is there an easier way to do this? I've seen a few (not a lot by any standards) posts which listed another method.
From this reddit post comment
// Add to webpack.config.js#module#loaders array
{
test: /[\/]angular\.js$/,
loader: "exports?angular"
}
There is also another plugin which is in development right now, at stackfull/angular-seed. It seems to be in the right direction, but is really really hard to use right now.
Webpack is way awesome, but the lack of documentation and samples are killing it.
You can just require angular in all modules (files) where you need it. I have a github repository with example how to do that (also using webpack for build). In the example ES6 import syntax is used but it shouldnt matter, you can use standard require() instead.
Example:
import 'bootstrap/dist/css/bootstrap.min.css';
import './app.css';
import bootstrap from 'bootstrap';
import angular from 'angular';
import uirouter from 'angular-ui-router';
import { routing} from './app.config';
import common from './common/common.module';
import featureA from './feature-a/feature-a.module';
import featureB from './feature-b/feature-b.module';
const app = angular
.module('app', [uirouter, common, featureA, featureB])
.config(routing);
I am starting with Angular + Flux with Webpack so may be I can help you with some things.
Basically I am installing everything with NPM, it has module export system, so it works like nothing. (You can use export-loader, but why if you do not need to.)
My webpack.config.js looks like this:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require("html-webpack-plugin");
var nodeModulesDir = path.resolve(__dirname, './node_modules');
// Some of my dependencies that I want
// to skip from building in DEV environment
var deps = [
'angular/angular.min.js',
...
];
var config = {
context: path.resolve(__dirname, './app'),
entry: ['webpack/hot/dev-server', './main.js'],
resolve: {
alias: {}
},
output: {
path: path.resolve(__dirname, './build'),
filename: 'bundle.js'
},
// This one I am using to define test dependencies
// directly in the modules
plugins: [
new webpack.DefinePlugin({
ON_TEST: process.env.NODE_ENV === 'test'
})
],
module: {
preLoaders: [
{test: /\.coffee$/, loader: "coffeelint", exclude: [nodeModulesDir]}
],
loaders: [
{test: /\.js$/, loader: 'ng-annotate', exclude: [nodeModulesDir]},
{test: /\.coffee$/, loader: 'coffee', exclude: [nodeModulesDir]},
...
],
noParse: []
},
devtool: 'source-map'
};
if (process.env.NODE_ENV === 'production') {
config.entry = {
app: path.resolve(__dirname, './app/main.js'),
vendors: ['angular']
};
// config.output.path = path.resolve(__dirname, './dist');
config.output = {
path: path.resolve(__dirname, "./dist"),
filename: "app.[hash].js",
hash: true
};
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.[hash].js'));
config.plugins.push(new HtmlWebpackPlugin({
title: 'myApp',
template: path.resolve(__dirname, './app/index.html'),
inject: 'body'
}));
delete config.devtool;
}
else {
deps.forEach(function (dep) {
var depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
}
module.exports = config;
My main.js looks like this:
var angular = require('angular');
if(ON_TEST) {
require('angular-mocks/angular-mocks');
}
require('./index.coffee');
And index.coffee containt main angular module:
ngModule = angular.module 'myApp', []
require('./directive/example.coffee')(ngModule)

Categories