Waypoint npm - Error: Can't resolve 'waypoint - javascript

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');

Related

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.

Webpack can't extract boostrap.css with min-css-extract plugin

I have a react application that I'm trying to extract the css into separate files but I'm having some issues here. I'm suing the MiniCssExtractPlugin for this. My current webpack configuration included below works fine when I include my own css files but it fails when I include my bootstrap.css from node_modules.
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import MyApp from './scenes/MyApp/MyApp'
import 'bootstrap/dist/css/bootstrap.css'
import './index.css'
import './assets/stylesheets/scenes.scss'
ReactDOM.render(<MyApp />, document.getElementById('root'))
webpack.config.js
const appConstants = function() {
switch (process.env.NODE_ENV) {
case 'local':
const localConfig = require('./config/local');
return localConfig.config();
case 'development':
const devConfig = require('./config/development');
return devConfig.config();
case 'production':
default:
const prodConfig = require('./config/production');
return prodConfig.config();
}
};
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
hash: true
});
let webpackConfig = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(css|scss)$/,
exclude: [/node_modules/],
include: [/node_modules\/bootstrap\/dist/],
use: [
{
loader: process.env.NODE_ENV !== 'local' ? MiniCssExtractPlugin.loader : 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(pdf|jpg|png|gif|svg|ico)$/,
exclude: [/node_modules/],
use: [
{
loader: 'file-loader'
},
]
},
{
test: /\.(woff|woff2|eot|ttf|svg|otf)$/,
exclude: [/node_modules/],
use: {
loader: 'url-loader?limit100000'
}
}
]
},
entry: [ "#babel/polyfill", "./src/index.js"],
output: {
publicPath: appConstants().DS_BASENAME ? JSON.parse(appConstants().DS_BASENAME) : '/'
},
optimization: {
splitChunks: {
chunks: 'all'
}
},
plugins: [
htmlWebpackPlugin,
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /en/),
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true,
statsOptions: { source: false }
}),
new webpack.DefinePlugin({
'process.env': appConstants()
}),
new webpack.EnvironmentPlugin(['NODE_ENV']),
new MiniCssExtractPlugin({
filename: (process.env.NODE_ENV == "local") ? "[name].css" : "[name].[hash].css",
chunkFilename: (process.env.NODE_ENV == "local") ? "[id].css" : "[id].[hash].css"
}),
new OptimizeCSSAssetsPlugin()
],
devServer: {
historyApiFallback: true,
port: 9090
},
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
};
// configure source map per-env
if (process.env.NODE_ENV === 'local') {
webpackConfig.devtool = 'eval-source-map';
} else {
webpackConfig.devtool = 'hidden-source-map';
}
module.exports = webpackConfig;
Here is the error I get during build:
ERROR in ./node_modules/bootstrap/dist/css/bootstrap.css 7:0
Module parse failed: Unexpected token (7:0)
You may need an appropriate loader to handle this file type.
| * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
| */
:root {
| --blue: #007bff;
| --indigo: #6610f2;
That error makes me think I'm missing the proper loader but I don't know what other loader I would need for this.
TL;DR
I want to extract all my css files including bootstrap.css into a separate file from my main.js .

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"
}

How to version CSS file in Webpack and update manifest?

I have a webpack config that has multiple JS entry points. In one of those entry points, I am requiring my styles: require('../sass/app.scss'); and then using a loader to extract the styles into another file app.css.
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!postcss-loader!sass-loader',
})
And that is working great. Of course, we are having issues with old styles being served when we deploy because they are not being versioned like our JS. I have been searching around for a few hours on how to do this and I cannot find a source on how to not only version the CSS, but also get a manifest file for the CSS. I tried creating a new instance of the versioning plugin that I am using, but it only created a manifest for the JS files. I am assuming that since I only have an output for JS that is the reason for this. Anyhow, here is my webpack.config.js:
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const CommonsPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const VersioningPlugin = require('versioning-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const routes = require('./resources/assets/js/routes');
module.exports = {
entry: routes,
devtool: 'eval-source-map',
output: {
path: path.join(__dirname, 'public/js'),
filename: '[name].[chunkhash:6].js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader?presets[]=env',
exclude: path.resolve(__dirname, 'node_modules/')
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!postcss-loader!sass-loader',
})
}
],
},
plugins: [
new CommonsPlugin({
minChunks: 3,
name: 'common'
}),
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: 'napaautocarepro.dev',
files: [
'public/css/app.css',
{
match: ['public/js/*.js', 'app/**/**/*.php', 'resources/views/**/**/*.php'],
fn: function(event, file) {
this.reload();
}
}
]
}, {
injectChanges: true,
reload: false
}),
new ExtractTextPlugin('../css/app.css'),
new VersioningPlugin({
cleanup: true,
basePath: 'js/',
manifestPath: path.join(__dirname, 'public/manifest.json')
}),
new WebpackMd5Hash()
]
};
And here is my weback.prod.config.js:
const config = require('./webpack.config');
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
config.plugins.unshift(
new CleanWebpackPlugin(['js', 'css'], {
root: path.join(__dirname, 'public'),
verbose: true,
dry: false,
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
comments: false,
sourceMap: true
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
canPrint: true,
cssProcessorOptions: { discardComments: { removeAll: true } }
})
);
module.exports = config;
How in the world can I version my CSS file and get it into a manifest so I can autoload the correct version?
Add [chunkhash] to the name of the file, something like:
plugins: [
//...
new ExtractTextPlugin('../css/app.[chunkhash].css'),
//...
]
(from https://github.com/webpack-contrib/extract-text-webpack-plugin#options )

"jQuery requires a window with a document" webpack 2 error

I bundled my node application with webpack2, I used JQuery with jade for my frontend. while run my application I am getting this error,
node_modules\jquery\dist\jquery.js:31
throw new Error( "jQuery requires a window with a document" );
^
Error: jQuery requires a window with a document
i used
var $ = require("jquery");
in all frontend javascript files.
I tried with this these solutions,
this to ,
{
test: require.resolve('jquery'),
loader: 'expose?$!expose?jQuery'
},
how I can handle this problem?
webpack.config.js
var path = require('path');
var nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
target: 'node',
entry: {
app: ['babel-polyfill', './bin/run.js'],
},
output: {
path: './build',
filename: '[name].min.js'
},
externals: [nodeExternals()],
plugins: [
new HtmlWebpackPlugin()
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /lodash/
},
{
test: /\.jade$/,
loader: 'jade-loader'
},
{
test: /\.css$/,
use: [
{loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true
}
}
]
},
],
noParse: [/ws/]
}
};
jQuery is to be used on the frontend (browser) only.
It looks like you are trying to use it in Node itself to reference back to $.
It's important to note that jQuery does not support server side rendering.
-> var $ = require("jquery"); won't work..

Categories

Resources