Cannot find module bundle - javascript

Somewhere in development this error started showing, I can't pinpoint where it comes from. The error is to 'broad' for my knowledge. I'm using webpack and gulp. If anyone can point me in the right direction.
I can post more code, but you'll need to tell me what files. The app works as it should, REST, pages loading, etc.. Only the css is not showing.
Starting gatling-rsync-deamon...
Starting containers...
Starting vagrant_redis_1
Starting vagrant_mongo_1
Starting vagrant_app_1
Connection to 127.0.0.1 closed.
launching stream...
[14:39:00] Requiring external module babel-register
[14:39:14] Using gulpfile /var/www/app/gulpfile.babel.js
[14:39:14] Starting 'set-dev-env'...
NODE_ENV will be set to development...
[14:39:14] Finished 'set-dev-env' after 310 μs
[14:39:14] Starting 'backend-watch'...
[14:39:14] Backend warming up...
[14:39:14] Starting 'frontend-watch'...
[14:39:15] Finished 'frontend-watch' after 694 ms
[14:39:15] Starting 'server'...
[14:39:15] Finished 'server' after 1.55 ms
Webpack-dev-server listening at localhost:9090.
module.js:340
throw err;
^
Error: Cannot find module '/var/www/app/build/bundle'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:945:3
[14:39:20] Finished 'backend-watch' after 5.25 s
[14:39:20] Starting 'dev'...
[14:39:20] Finished 'dev' after 3.46 μs
Hash: 5e15e9e5b2fd1c868120
Version: webpack 1.13.0
gulpfile.babel.js
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import gulp from 'gulp';
import gutil from 'gulp-util';
import nodemon from 'nodemon';
import path from 'path';
import jsdoc from 'gulp-jsdoc3';
import WebpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// import backendConfig from './config/webpack.backend.config.js';
// import frontendConfig from './config/webpack.frontend.config.js';
import configs from './config/webpack.config';
import jsdocConfig from './config/jsdoc.config';
const [frontendConfig, backendConfig] = configs;
const FRONTEND_PORT = 8085;
const BACKEND_PORT = 9090;
function onBuild(err, stats) {
if (err) {
throw new Error(err);
}
console.log(stats.toString());
}
// Default: list all tasks.
gulp.task('default', () => {
console.log('Available commands: dev, build');
});
// Start frontend
gulp.task('frontend', (done) => {
webpack(frontendConfig).run((err, stats) => {
onBuild(err, stats);
done();
});
});
// Start frontend watch
gulp.task('frontend-watch', () => {
const webpackDevserver = new WebpackDevServer(webpack(frontendConfig), {
publicPath: frontendConfig.output.publicPath,
stats: { colors: true },
historyApiFallback: true,
proxy: {
'*': `http://localhost:${BACKEND_PORT}`
}
});
webpackDevserver.listen(BACKEND_PORT, 'localhost', (err, result) => {
if (err) {
console.log(err);
}
else {
console.log(`Webpack-dev-server listening at localhost:${BACKEND_PORT}.`);
}
});
});
// Start backend
gulp.task('backend', (done) => {
webpack(backendConfig).run((err, stats) => {
onBuild(err, stats);
done();
});
});
// Start backend watch
gulp.task('backend-watch', (done) => {
gutil.log('Backend warming up...');
let firedDone = false;
webpack(backendConfig).watch(100, (err, stats) => {
if (!firedDone) { done(); firedDone = true; }
onBuild(err, stats);
nodemon.restart();
});
});
//
// gulp.task('run', ['set-dev-env', 'backend-watch'], () => {
// nodemon({
// execMap: {
// js: 'node'
// },
// script: path.join(__dirname, 'build/backend'),
// ignore: ['*'],
// watch: ['foo/'],
// ext: 'noop'
// }).on('restart', () => {
// console.log('Patched!');
// });
// });
// Set NODE_ENV to development
gulp.task('set-dev-env', () => {
console.log('NODE_ENV will be set to development...');
process.env.NODE_ENV = 'development';
});
// Set NODE_ENV to production
gulp.task('set-prod-env', () => {
console.log('NODE_ENV will be set to production...');
process.env.NODE_ENV = 'production';
});
// Start server
gulp.task('server', () => {
nodemon({
execMap: {
js: 'node'
},
script: path.join(__dirname, 'build/bundle'),
ignore: ['*'],
watch: ['foo/'],
ext: 'noop'
}).on('restart', () => {
console.log('Server restarted!');
});
});
// Generate docs
gulp.task('docs', (cb) => {
// gulp.src(['README.md', './client/**/*.js', './server/**/*.js'], { read: false })
// .pipe(jsdoc(jsdocConfig, cb));
});
// Build project
gulp.task('build', ['set-prod-env', 'build-js']);
// Build backend & frontend
gulp.task('build-js', ['backend', 'frontend']);
// Watch backend & frontend
gulp.task('watch', ['backend-watch', 'frontend-watch']);
// Start development session
gulp.task('dev', ['set-dev-env', 'backend-watch', 'frontend-watch', 'server']);
webpack.config
import webpack from 'webpack';
import path from 'path';
import fs from 'fs';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const embedFileSize = 50000;
const nodeModules = {};
fs.readdirSync('node_modules')
.filter(module => {
return ['.bin'].indexOf(module) === -1;
})
.forEach(mod => {
nodeModules[mod] = 'commonjs ' + mod;
});
const frontendConfig = {
entry: [
'webpack-hot-middleware/client',
path.join(__dirname, '../client/index.js')
],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'build', 'public')
},
devtool: 'sourcemap',
plugins: [
new HtmlWebpackPlugin({
template: './client/public/index.html',
inject: 'body',
filename: 'index.html'
}),
new webpack.ProvidePlugin({
'Promise': 'es6-promise',
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'),
'__DEV__': JSON.stringify(process.env.NODE_ENV)
})
],
module: {
preloaders: [
{ test: /\.js$/, loader: 'eslint'}
],
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.json?$/,
loader: 'json'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules&&importLoaders=1&localIdentName=[name]---[local]---[hash:base64:5]!postcss-loader'
},
{
test: /\.less$/,
loader: "style!css!less"
},
{ test: /\.svg/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/svg+xml'
},
{ test: /\.png$/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/png'
},
{ test: /\.jpg/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/jpeg'
},
{ test: /\.gif/,
loader: 'url?limit=' + embedFileSize + '&mimetype=image/gif'
},
{
test: /\.(otf|eot|ttf|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?limit=' + embedFileSize
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.css']
},
};
const serverConfig = {
entry: './server/server.js',
output: {
path: path.join(__dirname, '../build'),
filename: 'bundle.js'
},
devtool: 'sourcemap',
target: 'node',
// do not include polyfills or mocks for node stuff
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false
},
externals: nodeModules,
plugins: [
// enable source-map-support by installing at the head of every chunk
new webpack.BannerPlugin('require("source-map-support").install();',
{raw: true, entryOnly: false})
],
module: {
loaders: [
{
// transpile all .js files using babel
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
}
]
}
};
export default [frontendConfig, serverConfig];

My answer for now is based on your pasted code. When I get more info, then I will edit this answer.
Im not sure If I can find remotely correct solution for you. But your problem is probably with public path which is added to webpack and to WebpackDevServer. WebpackDevServer doesn't see your js code which is bundled in bundle.js

Change your target to "web" instead of node. You should compile for a web type of environment most likely and not a node.js like environment.
target: 'web',

Related

WebPack output.library.type var is undefined

I am learning WebPack with a shortcode. In the code, we are trying to calculate the cube and square. They will suppose to store in a variable as per the following webpack.config.js.
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const isDevelopment = process.env.NODE_ENV === 'development';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
library: {
type: 'var',
name: 'testVar'
},
filename: '[name].js'
},
mode: 'production',
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
new HtmlWebpackPlugin({
hash: true,
title: 'Video Player Play Ground',
myPageHeader: 'Sample Video Player',
template: './src/index.html',
filename: 'index.html'
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
exclude: /node_modules/,
use: [
// fallback to style-loader in development
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
{
test: /\.ts(x)?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.svg$/,
use: 'file-loader'
}
]
},
resolve: {
extensions: [
'.tsx',
'.ts',
'.js',
'.scss'
]
},
optimization: {
usedExports: true,
runtimeChunk: false,
minimize: false
}
};
module.exports = config;
As shown in the above config, we store the compiled javascript in the variable with the name "testVar".
The above approach working fine when we are using the following command line code "webpack --mode production"
In the final generated javascript file we have a line which equals to
testVar = webpack_exports;
Also, testVar.start is working fine.
But the above approach is not working when we are using the following command line "webpack serve --mode production" or "webpack serve"
When we run a local server, the testVar.start is undefined. I am not sure what I am doing wrong.
Following is the code we are using in the index.html file to call the start function, which we defined in our internal javascript
window.onload = function (){
alert(testVar);
console.log(testVar);
if(testVar.start !== undefined)
{
alert(testVar.start);
console.log(testVar.start);
testVar.start(3,2);
}
else {
alert("Start Function is undefined");
}
}
Also following is the code insight from index.ts and math.ts.
import {cube, square} from './math';
export function start(c:number, s:number) {
console.log(cube(c));
console.log(square(s));
}
export function square(x:number) {
return x * x;
}
export function cube(x:number) {
return x * x * x;
}
enter image description here
Finally, I got it working :-).
I need to add the following line in my webpack.config.js
devServer: {
injectClient: false
},
Following is the reference URL: https://github.com/webpack/webpack-dev-server/issues/2484
Don't forget to Vote it. Thanks.

Cannot find module 'jsonfile/utils' in Electron-Typescript app

I started from a brand new working very simple Electron-Typescript app.
In this working really simple Electron-Typescript app, I added in main.ts:
import Ipfs from 'ipfs';
import IpfsHttpClient from 'ipfs-http-client';
and this import of ipfs modules went fine.
But when I add
const { globSource } = IpfsHttpClient;
or
when I create an IPFS node:
const ops = async () => {
const node = await Ipfs.create({ repo: String(Math.random() + Date.now()) });
}
I get this error:
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module 'jsonfile/utils'
at webpackMissingModule (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack/main/index.js:13356:87)
at Object../node_modules/fs-extra/lib/json/output-json.js (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack
/main/index.js:13356:176)
at __webpack_require__ (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack/main/index.js:21:30)
at Object../node_modules/fs-extra/lib/json/index.js (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack
/main/index.js:13284:25)
at __webpack_require__ (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack/main/index.js:21:30)
at Object../node_modules/fs-extra/lib/index.js (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack
/main/index.js:13250:6)
at __webpack_require__ (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack/main/index.js:21:30)
at Object../node_modules/ipfs-utils/src/files/glob-source.js (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack
/main/index.js:25171:12)
at __webpack_require__ (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack/main/index.js:21:30)
at Object../node_modules/ipfs-http-client/src/index.js (/home/marco/webMatters/electronMatters/IpfsPlaying/.webpack
/main/index.js:21670:20)
tools/webpack/webpack.main.js :
module.exports = {
entry: ['./src/main.ts'],
// Put your normal webpack config below here
module: {
rules: require('./webpack.rules'),
},
resolve: {
extensions: ['.js', '.ts', '.jsx', '.tsx', '.css', '.json'],
alias: require('./webpack.aliases'),
},
target: 'electron-main'
};
tools/webpack/webpack.renderer.js :
/* eslint-disable #typescript-eslint/no-var-requires */
const rules = require('./webpack.rules');
const plugins = require('./webpack.plugins');
const aliases = require('./webpack.aliases');
module.exports = {
target: 'electron-renderer',
module: {
rules,
},
plugins: plugins,
resolve: {
extensions: ['.js', '.ts', '.jsx', '.tsx', '.css'],
alias: {
// React Hot Loader Patch
'react-dom': '#hot-loader/react-dom',
// Custom Aliases
...aliases,
},
},
};
tools/webpack/webpack.rules.js :
const inDev = process.env.NODE_ENV === 'development';
module.exports = [
{
// Add support for native node modules
test: /\.node$/,
use: 'node-loader',
},
{
// Typescript loader
test: /\.tsx?$/,
exclude: /(node_modules|\.webpack)/,
use: {
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
},
{
// CSS Loader
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
},
{
// Less loader
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'less-loader' },
],
},
{
// Images Loader
test: /\.(gif|jpe?g|tiff|png|webp|bmp)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: 'images',
outputPath: inDev ? 'images' : './main_window/images',
},
},
],
},
];
If modify the target from electron-renderer' to web' in
tools/webpack/webpack.renderer.js :
/* eslint-disable #typescript-eslint/no-var-requires */
const rules = require('./webpack.rules');
const plugins = require('./webpack.plugins');
const aliases = require('./webpack.aliases');
module.exports = {
//target: 'electron-renderer',
target: 'web',
module: {
rules,
},
plugins: plugins,
resolve: {
extensions: ['.js', '.ts', '.jsx', '.tsx', '.css'],
alias: {
// React Hot Loader Patch
'react-dom': '#hot-loader/react-dom',
// Custom Aliases
...aliases,
},
},
};
And in the renderer process /src/app/components/App.tsx I add :
import Ipfs from 'ipfs';
const { globSource } = Ipfs;
const ops = async () => {
const node = await Ipfs.create({ repo: String(Math.random() +
Date.now()) });
console.log('Ipfs node is ready');
const files = [
{
path: '/home/marco/Downloads/Art21Costituzione.jpg',
content: 'Art21Costituzione'
},
{
path: '/home/marco/Downloads/VitaminaCAlimenti.pdf',
content: 'VitaminaCAlimenti'
}
];
let results = await all(node.addAll(files));
results.map(result => console.log(result));
}
I get this correct output:
But globSource in the renderer process gives error:
for await (const file of node.addAll(globSource('/home/marco
/Downloads', globSourceOptions), addOptions)) {
console.log(file);
}
So.. I guess there is something to fix in webpack configuration in order to make it work in the main process,
instead of having it in the renderer process.
How to solve the problem?
Just install jsonfile
yarn add jsonfile
worked for me!
https://www.npmjs.com/package/jsonfile
You can use webpack-config-utils module to solve this problem.
npm install --save-dev webpack-config-utils
The detailed instruction is described here

ERROR in ./src/App.jsx Module not found: Error: Can't resolve './component/Footer'

I'm working on a react-app change to SSR using Koa.
but can't resolve folder. It works well in CSR....
**ERROR in ./src/App.jsx
Module not found: Error: Can't resolve './component/Footer' in '/mnt/c/Users/moidp/CloudStation/sangwook/Programing/project/blog/blog-frontend/src'
# ./src/App.jsx 18:0-40 129:27-33enter code here
# ./src/ssr/render.js
ERROR in ./src/App.jsx
Module not found: Error: Can't resolve './component/NavBar' in '/mnt/c/Users/moidp/CloudStation/sangwook/Programing/project/blog/blog-frontend/src'
# ./src/App.jsx 17:0-40 105:25-31
# ./src/ssr/render.js**
webpack.config.server.js
'use strict';
const nodeExternals = require('webpack-node-externals');
const paths = require('./paths');
const webpack = require('webpack');
const getClientEnvironment = require('./env');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const publicUrl = paths.servedPath.slice(0, -1);
const env = getClientEnvironment(publicUrl);
module.exports = {
mode: 'production', // 프로덕션 모드로 설정하여 최적화 옵션들을 활성화
entry: paths.serverRenderJs, // 엔트리 경로
target: 'node', // node 환경에서 실행 될 것이라는 것을 명시
output: {
path: paths.ssrBuild, // 빌드 경로
filename: 'server.js', // 파일이름
chunkFilename: 'js/[name].chunk.js', // 청크 파일이름
publicPath: paths.servedPath, // 정적 파일이 제공 될 경로
},
module: {
rules: [
{
oneOf: [
// 자바스크립트를 위한 처리
// 기존 webpack.config.js 를 참고하여 작성
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve('babel-preset-react-app/webpack-overrides'),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent: '#svgr/webpack?-svgo![path]',
},
},
},
],
],
cacheDirectory: true,
cacheCompression: false,
compact: false,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[require.resolve('babel-preset-react-app/dependencies'), { helpers: true }],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false,
},
},
// CSS 를 위한 처리
{
test: cssRegex,
exclude: cssModuleRegex,
// onlyLocals: true 옵션을 설정해야 실제 css 파일을 생성하지 않습니다.
loader: require.resolve('css-loader'),
options: {
onlyLocals: true,
},
},
// CSS Module 을 위한 처리
{
test: cssModuleRegex,
loader: require.resolve('css-loader'),
options: {
modules: true,
onlyLocals: true,
getLocalIdent: getCSSModuleLocalIdent,
},
},
// Sass 를 위한 처리
{
test: sassRegex,
exclude: sassModuleRegex,
use: [
{
loader: require.resolve('css-loader'),
options: {
onlyLocals: true,
},
},
require.resolve('sass-loader'),
],
},
// Sass + CSS Module 을 위한 처리
{
test: sassRegex,
exclude: sassModuleRegex,
use: [
{
loader: require.resolve('css-loader'),
options: {
modules: true,
onlyLocals: true,
getLocalIdent: getCSSModuleLocalIdent,
},
},
require.resolve('sass-loader'),
],
},
// url-loader 를 위한 설정
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
emitFile: false, // 파일을 따로 저장하지 않는 옵션
limit: 10000, // 원래는 9.76KB가 넘어가면 파일로 저장하는데
// emitFile 값이 false 일땐 경로만 준비하고 파일은 저장하지 않습니다.
name: 'static/media/[name].[hash:8].[ext]',
},
},
// 위에서 설정된 확장자를 제외한 파일들은
// file-loader 를 사용합니다.
{
loader: require.resolve('file-loader'),
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
emitFile: false, // 파일을 따로 저장하지 않는 옵션
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
],
},
resolve: {
modules: ['node_modules'],
},
externals: [nodeExternals()],
plugins: [
new webpack.DefinePlugin(env.stringified), // 환경변수를 주입해줍니다.
],
};
on App.jsx
import { Home, Editor, Post, About, Auth } from './pages';
import NavBar from './component/NavBar';
import Footer from './component/Footer';
path.js
const path = require('path');
const fs = require('fs');
const url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(inputPath, needsSlash) {
const hasSlash = inputPath.endsWith('/');
if (hasSlash && !needsSlash) {
return inputPath.substr(0, inputPath.length - 1);
} if (!hasSlash && needsSlash) {
return `${inputPath}/`;
}
return inputPath;
}
const getPublicUrl = (appPackageJson) => envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl = envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find((extension) =>
fs.existsSync(resolveFn(`${filePath}.${extension}`)),
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
serverRendenJs: resolveApp('src/server/render.js'),
server: resolveApp('server/render'),
};
module.exports.moduleFileExtensions = moduleFileExtensions;
It seems webpack might not know how to resolve the .jsx file extensions for your /Footer.jsx and /NavBar.jsx files.
This problem might be solved by adding .jsx to resolve.extensions like so:
resolve: {
modules: ['node_modules'],
extensions: ['.js', '.jsx', '.ts', '.tsx', ...]
},
check your package.json and you can try this;
rm -rf node_modules && yarn install
I guess you have not imported the correct path to Footer and NavBar components in your App.jsx file and you're trying to render those two incorrectly imported components in App.jsx.
Can you please share your complete App.jsx file and the folder structure of your project to pinpoint the error better.

module.exports error for webpack backend (node.js)

I'm trying to use webpack to bundle my backend code. It's currently using vanilla node.js where I'm using module.exports.x, and when I run webpack, it also outputs the export line i.e. module.exports.x. Now the problem is when I run nodemon on the file, it gives me the error TypeError: Cannot set property 'x' of undefined.
What's my resolution here?
my config file.
"use strict"
const path = require("path")
// const utils = require("./utils")
// const config = require("../config")
var fs = require("fs")
const NodemonPlugin = require("nodemon-webpack-plugin")
const nodeExternals = require("webpack-node-externals")
function resolve(dir)
{
return path.join(__dirname, "..", dir)
}
module.exports = {
context: path.resolve(__dirname, "../"),
entry: "./src/server/server.js",
output: {
path: path.resolve(__dirname, "../src/server"),
filename: "server-webpack.js",
},
plugins: [
new NodemonPlugin(),
],
resolve: {
extensions: [".js",".ts", ".tsx"],
alias: {
"#": resolve("src"),
"#": resolve("src/server")
}
},
devtool: "#inline-source-map",
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
include: [resolve("src"), resolve("test")]
},
{
test: /\.tsx?$/,
loader: "ts-loader",
},
]
},
externals: [
nodeExternals()
],
target: "node"
}

Waypoint npm - Error: Can't resolve 'waypoint

I have a vue project and installed waypoints
npm install waypoints
I try to import it
import waypoint from 'waypoints';
but get an error
Error: Can't resolve 'waypoints' in /Mypath
What am I doing wrong?
var webpack = require('webpack');
var path = require('path');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
var WebpackNotifierPlugin = require('webpack-notifier');
var fs = require('file-system');
var CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
/*node: {
fs: "empty"
},*/
resolve: {
alias: {
'masonry': 'masonry-layout',
'isotope': 'isotope-layout'
}
},
entry: './main.js',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, './public/assets'),
filename: 'bundle.[chunkhash].js',
},
module: {
rules: [
{ test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader?presets[]=es2015",
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
use: [{loader:'css-loader?sourceMap'}, {loader:'sass-loader', options: {
sourceMap: true,
}}],
})
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
]
},
plugins: [
new CleanWebpackPlugin(['assets/*', 'css/*'], {
root: '/Users/LEITH/sites/laravelleith/public',
verbose: true,
dry: false,
exclude: ['360lockturret.jpg'],
watch: true
}),
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('app.[chunkhash].css'),
new WebpackNotifierPlugin(),
function() {
this.plugin('done', stats =>{
fs.writeFileSync(
path.join(__dirname, 'manifest.json'),
JSON.stringify(stats.toJson().assetsByChunkName)
)
});
}
]
};
Waypoints comes bundled in several flavours, even via NPM, but I couldn't work out if there's a default implementation or not. So that's why your typical import Waypoint from 'waypoints' directive doesn't work.
I resolved this for my "vanilla ES6 + Webpack" setup as follows:
import 'waypoints/lib/noframework.waypoints.min.js';
const waypoint = new Waypoint({
element: document.getElementById('myScrollTarget'),
handler: () => {}
});
Basically #markedup is right, waypoints comes with various flavours, after installing waypoints if you look into /waypoints/lib/ folder you will see zepto|jquery|noframework.waypoints.js .
In this case you would require to import it as full path i.e.
import 'waypoints/lib/noframework.waypoints.min.js';
or
window.waypoint = require('waypoints/lib/noframework.waypoints');

Categories

Resources