Webpack cannot resolve custom JS file - javascript

We are trying to migrate from grunt to webpack.
In our project, we use a JS file called boiler to define the frequently accessed core classes.
__boiler__.js
define(function (require) {
return {
Helpers: require('helpers/_helpers_'),
Enums: require('enums/_enums_'),
Context: require('context'),
...
};
});
And Web Pack Config
webpack.config.js
const path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.scss'],
alias: {
app: path.resolve(__dirname, './dev_files/app'),
Boiler: path.resolve(__dirname, './dev_files/app/core/_boiler_')
}
},
entry: './dev_files/main.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.(html)$/,
use: {
loader: 'html-loader'
}
},
{
test: /\.js$/,
use: ['babel-loader']
}
]
}
};
Then when I tried to do webpack build, it gave me some errors like:
ERROR in ./dev_files/app/core/_boiler_.js
Module not found: Error: Can't resolve 'context' in 'C:\Myproject\dev_files\app\core'
resolve 'context' in 'C:\Myproject\dev_files\app\core'
Parsed request is a module
using description file: C:\Myproject\package.json (relative path: ./dev_files/app/core)
Field 'browser' doesn't contain a valid alias configuration
resolve as module
....
I'm a noob when in JavaScript and WebPack in general. Could someone give me an idea what am I doing wrong here? Thanks.

I assume you are using require for your module loading.
try to export your definition so that it can be found/included by webpack
module.export = (function (require) {
return {
Helpers: require('helpers/_helpers_'),
Enums: require('enums/_enums_'),
Context: require('context'),
// ...
};
});

Related

Webpack loads in wrong from parent folder

I am trying to run a watch command on my Webpack in order to compile my code but I always face an issue with my file. Even trying to change the relative paths with some ../ did not work
ERROR in code
Module not found: Error: Can't resolve '../src/code.ts' in '/Users/giardiv/Lines/f-variables'
ERROR in ui
Module not found: Error: Can't resolve '../src/ui.tsx' in '/Users/giardiv/Lines/f-variables'
ERROR in Error: Child compilation failed:
Module not found: Error: Can't resolve '/Users/giardiv/Lines/src/ui.html' in ' /Users/giardiv/Lines/f-variables':
Error: Can't resolve '/Users/giardiv/Lines/src/ui.html' in '/Users/giardiv/Lin es/f-variables'
ModuleNotFoundError: Module not found: Error: Can't resolve '/Users/giardiv/Li nes/src/ui.html' in '/Users/giardiv/Lines/f-variables'
While my folder tree is quite basic, f-variables is the src and other files are directly in it
This is the webpack config
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = (env, argv) => ({
mode: argv.mode === 'production' ? 'production' : 'development',
// This is necessary because Figma's 'eval' works differently than normal eval
devtool: argv.mode === 'production' ? false : 'inline-source-map',
entry: {
ui: "../src/ui.tsx", // "./src/ui.tsx" calls the same error
code: "../src/code.ts" // "./src/code.ts" calls the same error
},
module: {
rules: [
// Converts TypeScript code to JavaScript
{ test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },
// Enables including CSS by doing "import './file.css'" in your TypeScript code
{ test: /\.css$/, use: ['style-loader', { loader: 'css-loader' }] },
// Allows you to use "<%= require('./file.svg') %>" in your HTML code to get a data URI
{ test: /\.(png|jpg|gif|webp|svg)$/, loader: 'url-loader' },
],
},
// Webpack tries these extensions for you if you omit the extension like "import './file'"
resolve: { extensions: ['.tsx', '.ts', '.jsx', '.js'] },
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'), // Compile into a folder called "dist"
publicPath: '/',
},
// Tells Webpack to generate "ui.html" and to inline "ui.ts" into it
plugins: [
new HtmlWebpackPlugin({
template: '../src/ui.html',
filename: 'ui.html',
inlineSource: '.(js)$',
chunks: ['ui'],
}),
new HtmlWebpackInlineSourcePlugin(HtmlWebpackPlugin),
],
})
Because the paths in entry are wrong in your webpack.config.js file.
It should be set as below since you have webpack.config.js besides src directory.
entry: {
ui: "./src/ui.tsx",
code: "./src/code.ts"
},

React : You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file(Local Node module)

I have babel loader in the library. Still after I add the library to the react application while yarn serve, I get the above error.
This is the webpack.dev.config.js (required in the webpack.config.js) in library-
//webpack.dev.config.js
const babelRCPath = require('#appfabric/infra-scripts').getConfigPath('babel', 'plugin');
const babelRCGenerator = require(babelRCPath);
const babelRC = babelRCGenerator([]);
module.exports = {
{
BaseModule: `${process.cwd()}/src/BaseModule`,
BaseObject: `${process.cwd()}/src/BaseObject`,
BaseWidget: `${process.cwd()}/src/widgets/BaseWidget`,
HOCWidget: `${process.cwd()}/src/widgets/HOCWidget`,
PortalWidget: `${process.cwd()}/src/widgets/PortalWidget`,
BaseActivator: `${process.cwd()}/src/application/BaseActivator`,
CorePlugin: `${process.cwd()}/src/application/CorePlugin`,
BaseAppDelegate: `${process.cwd()}/src/application/appdelegates/BaseAppDelegate`,
EmbeddedAppDelegate: `${process.cwd()}/src/default/appdelegates/embedded/EmbeddedAppDelegate`,
ActionType: `${process.cwd()}/src/application/appdelegates/actions/ActionType`,
types: `${process.cwd()}/src/application/appdelegates/actions/types`,
CommandActionType: `${process.cwd()}/src/application/appdelegates/actions/CommandActionType`,
CommandForResponseActionType: `${process.cwd()}/src/application/appdelegates/actions/CommandForResponseActionType`,
PluginRegistryService: `${process.cwd()}/src/default/PluginRegistryService`,
},
mode: 'development',
externals: [
'dcl',
'react',
'react-dom',
'prop-types',
'pubsub',
'semver',
'#appfabric/ui-profiler',
].map(
// Add this regex to each entry to ensure we don't miss any imports like 'web-shell-core/...`
(value) => new RegExp(`^(${value})((\\\\|/|!).+)?$`),
),
output: {
path: `${process.cwd()}/build/dist`,
filename: '[name].js',
library: 'web-shell-core',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: babelRC,
},
},
],
},
};
This is the webpack.config.js
const developmentConfig = require('./webpack.dev.config.js');
module.exports = merge(developmentConfig, {
mode: 'production',
output: {
filename: '[name].min.js',
chunkFilename: '[name].min.js',
},
});
First I add a new file Secure.jsx(having the tags) in the library. I do npm install --save <path-to-library> on my application. After I do yarn install. Then I can see the new file Secure.jsx in the node modules in the application. When I try to run the application, I get the error.
Please let me know what am I missing and also which side(library / application) I have to add the code.
You can view my full config here
I think you also need to add this
resolve: {
modules: [
path.resolve('./node_modules')
]
},
Then import like this
import "jquery/dist/jquery.min.js";
import "bootstrap/dist/js/bootstrap.min.js";

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.

How to force Webpack 3 to throw TypeScript errors?

// index.ts
let a = 1;
a.map();
Webpack doesn't throw this TS error about method "map" on type "number.
Do you know how check these errors automatically during webpack build?
Can't find anything on the internet.
Previously I saw this: https://cloud.githubusercontent.com/assets/376414/7276837/840b4dec-e8da-11e4-8362-c44f531d8cd9.png
How can I get the same output of webpack (TS errors) using webpack 3?
TypeScript thinks it's ok (any valid JS is also valid TypeScript), so, any project could be bundled with any JS error.
If I'm running tsc app/index.ts then I see the error:
app/index.ts(8,3): error TS2339: Property 'map' does not exist on type 'number'.
So, TypeScript compiler throws the error, but webpack (ts-loader I think) ignores it.
I'm using webpack 3.8.1
Here is config:
let path = require('path'),
webpack = require('webpack'),
HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.resolve('app/index.ts'),
output: {
path: path.resolve('dist'),
filename: 'app.js'
},
resolve: {
extensions: ['.js', '.vue', '.json', '.ts'],
alias: {
vue: path.resolve('node_modules/vue/dist/vue.js'),
app: path.resolve('app')
}
},
module:{
rules: [
{ test: /\.tsx$/, use: 'ts-loader' },
{ test: /\.vue$/, use: 'vue-loader' },
{ test: /\.pug$/, use: 'pug-loader' }
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('app/index.pug'),
cache: false
}),
new webpack.LoaderOptionsPlugin({
debug: true
})
]
};
do you ever heard about linting? here's the loader for tslint for webpack

Angular 4 universal app with #angular/cli with third party (library/component) compilation

I am trying to implement server side rendering using angular universal. With followed this post angular-4-universal-app-with-angular-cli and this cli-universal-demo project, I encountered a problem as below.
When node starts dist/server.js it shows an error:
(function (exports, require, module, __filename, __dirname)
{ export * from ‘./scn-filter-builder’
scn-filter-builder is my module. It's written in angular2/typescript and node.js doesn't understand it.
The question is that can I set to universal so it will compile packages from node_module to es5 by itself? Or I need to compile my component into es5?
So I ended up tackling something similar to this by compiling it with Webpack. I just added a webpack.config.js with the following:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: {
server: './src/server.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
target: 'node',
externals: [nodeExternals({
whitelist: [
/^ngx-bootstrap/
]
})],
node: {
__dirname: true
},
output: {
path: path.join(__dirname, 'server'),
filename: '[name].js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{ test: /\.ts$/, loader: 'ts-loader' }
]
}
}
Add the library that needs to be compiled in the nodeExternals -> whitelist area. In my case it was ngx-bootstrap. Then just run webpack to compile your file.

Categories