Issues importing a library - javascript

I've recently came across a interact.js, a library that I want to use in one of my projects, but I cant get it to work.
I've installed it via npm
npm install interactjs --save
It shows up in my package.json dependency as
"dependencies": {
"angular": "^1.6.4",
"angular-ui-router": "^0.4.2",
"interactjs": "^1.2.9"
}
And I've also imported it in main.js where I import other libs and modules
import 'interactjs';
The project being in angularjs, I've used some interact.js syntax inside a function within my controller, but I get the following error:
app.js:57837 Uncaught Error: Module parse failed: path\controller.js Unexpected token (207:48)
You may need an appropriate loader to handle this file type.
| drag() {
| let drag = document.querySelector('.draggable');
| interact(drag).draggable({ inertia: true; })
| }
|
at Object.__webpack_require__.constructor.options.count (app.js:57837)
at __webpack_require__ (app.js:658)
at fn (app.js:86)
at Object.__webpack_exports__.a (app.js:57778)
at __webpack_require__ (app.js:658)
at fn (app.js:86)
at Object.<anonymous> (app.js:57896)
at __webpack_require__ (app.js:658)
at fn (app.js:86)
at Object.module.exports (app.js:5219)
I'm guessing it has something to do with webpack and not the library itself ?
EDIT: webpack.config.js
const path = require('path');
const webpack = require('webpack');
/**
* Plugins
*/
const HtmlWebpackPlugin = require('html-webpack-plugin');
/**
* Env. vars
*/
const port = process.env.PORT || 3000;
const hostname = process.env.HOSTNAME || 'localhost';
const host = 'http://' + hostname + ':' + port;
const assetHost = process.env.ASSET_HOST || host + '/';
const paths = {
source: 'src',
dist: 'public'
};
module.exports = {
entry: {
app: [
path.resolve('src/main.js'),
'webpack-dev-server/client?' + host,
'webpack/hot/only-dev-server'
]
},
output: {
path: path.join(process.cwd(), 'public'),
filename: '[name].js',
chunkFilename: '[chunkhash].[name].js'
},
resolveLoader: {
modules: ['node_modules']
},
resolve: {
modules: [
'devtools',
'src',
'node_modules'
],
extensions: ['.ts', '.js', '.json', '.scss', '.css', '.html', '.jpg', '.png'],
alias: {
'game': path.resolve('src/modules/game')
}
},
node: {
global: true,
process: true,
console: true,
fs: 'empty'
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('src/index.ejs'),
inject: 'head'
}),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
inline: true,
port: port,
publicPath: assetHost, // Make sure publicPath always starts and ends with a forward slash.
contentBase: [
path.join(process.cwd(), paths.source),
path.join(process.cwd(), paths.dist)
],
clientLogLevel: 'none',
noInfo: true,
historyApiFallback: {
disableDotRule: true
}
},
module: {
rules: [
{
test: /\.html$/,
exclude: /node_modules/,
use: [
{
loader: 'html-loader'
}
]
},
{
test: /\.(jpe?g|gif|png|woff|woff2|eot|ttf|svg)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
options: {
includePaths: [
// path.resolve('node_modules/xbem/src/'),
// path.resolve('src/themes/' + config.theme)
]
}
}
]
}
]
}
}

Related

Webpack breaking change

I am trying to build a react app but each time I run npm start, I am greeted with this message
Module not found: Error: Can't resolve 'buffer' in '/Users/abdus/Documents/GitHub/keywords-tracker/node_modules/buffer-equal-constant-time'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
It gives the same message for a few different modules. I have tried npm installing these modules but the error persists
this is my webpack set up that works. you should install all the packages that listed in fallback:
// const path = require("path");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const webpack = require("webpack");
module.exports = {
mode: "development",
target: "web",
entry: ["regenerator-runtime/runtime", "./src/index.js"],
output: {
filename: "bundle.js",
path: path.join(__dirname, "dist"),
publicPath: "/",
},
resolve: {
extensions: [".js", ".css"],
alias: {
// add as many aliases as you like!
components: path.resolve(__dirname, "src/components"),
},
fallback: {
// path: require.resolve("path-browserify"),
fs: false,
assert: require.resolve("assert/"),
os: require.resolve("os-browserify/browser"),
constants: require.resolve("constants-browserify"),
stream: require.resolve("stream-browserify"),
crypto: require.resolve("crypto-browserify"),
http: require.resolve("stream-http"),
https: require.resolve("https-browserify"),
},
},
// devtool: "eval-cheap-source-map",
devtool: "eval",
module: {
rules: [
{ test: /\.(js|jsx)/, loader: "babel-loader", exclude: /node_modules/ },
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
// {
// test: /\.m?js/,
// resolve: {
// fullySpecified: false
// }
// },
{
test: /\.(woff(2)?|ttf|eot|jpg|jpeg|png|gif)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[contenthash].[ext]",
outputPath: "fonts/",
},
},
],
},
{
test: /\.svg$/,
use: [
{
loader: "svg-url-loader",
options: {
limit: 10000,
},
},
],
},
{
test: /\.json5$/i,
loader: "json5-loader",
type: "javascript/auto",
options: {
esModule: true,
},
},
],
},
devServer: {
contentBase: path.join(__dirname, "build"),
historyApiFallback: true,
overlay: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "NFT",
template: "src/index.html",
}),
// new CopyWebpackPlugin({
// patterns: [{ from: "assets", to: "assets" }],
// }),
],
};
you can get this webpack5-Boilerplate
Since there are too many polyfills, instead of manually installing all, you can use node-polyfill-webpack-plugin package. instead of fallback property
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
plugins: [
new HtmlWebpackPlugin({
title: "esBUild",
template: "src/index.html",
}),
// instead of fallback
new NodePolyfillPlugin(),
// new webpack.ProvidePlugin({
// process: "process/browser",
// Buffer: ["buffer", "Buffer"],
// React: "react",
}),
],
It seems like you are using a front-end react app and some dependency is internally using the buffer module which is only available in target: node under webpack. So you will need to add a polyfill for the same.
module.exports = {
resolve: {
fallback: {
buffer: require.resolve('buffer'),
}
},
}
You can check the docs here at webpack: https://webpack.js.org/configuration/resolve/#resolvefallback
From Webpack 5 onwards, webpack doesn't polyfill for browser-based applications.

How to resolve to a non default javascript file

I am using webpack and typescript in my SPA along with the oidc-client npm package.
which has a structure like this:
oidc-client.d.ts
oidc-client.js
oidc-client.rsa256.js
When I import the oidc-client in my typescript file as below:
import oidc from 'oidc-client';
I want to import the rsa256 version and not the standard version, but I am unsure how to do this.
in my webpack config I have tried to use the resolve function but not I am not sure how to use this properly:
const path = require('path');
const ForkTsChecker = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
const shell = require('shelljs');
const outputFolder = 'dist';
const destinationFolder = '../SPA/content';
if (shell.test('-d', outputFolder)) {
shell.rm('-rf', `${outputFolder}`);
}
if (shell.test('-d', destinationFolder)) {
shell.rm('-rf', `${destinationFolder}`);
}
module.exports = (env, options) => {
//////////////////////////////////////
/////////// HELP /////////////////////
/////////////////////////////////////
resolve: {
oidc = path.resolve(__dirname, 'node_modules\\oidc-client\\dist\\oidc- client.rsa256.slim.min.js')
};
const legacy = GenerateConfig(options.mode, "legacy", { "browsers": "> 0.5%, IE 11" });
return [legacy];
}
function GenerateConfig(mode, name, targets) {
return {
entry: `./src/typescript/main.${name}.ts`,
output: {
filename: `main.${name}.js`,
path: path.resolve(__dirname, `${outputFolder}`),
publicPath: '/'
},
resolve: {
extensions: ['.js', '.ts']
},
stats: {
children: false
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.ts\.html?$/i,
loader: 'vue-template-loader',
},
{
test: /\.vue$/i,
loader: 'vue-loader'
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'#babel/env',
{
"useBuiltIns": "usage",
"corejs": { version: 3, proposals: true },
"targets": targets
}
],
"#babel/typescript"
],
plugins: [
"#babel/transform-typescript",
[
"#babel/proposal-decorators",
{
"legacy": true
}
],
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/proposal-class-properties",
"#babel/proposal-numeric-separator",
"babel-plugin-lodash",
]
}
}
}
]
},
devServer: {
contentBase: path.join(__dirname, outputFolder),
compress: true,
hot: true,
index: `index.${name}.html`,
open: 'chrome'
},
plugins: [
new ForkTsChecker({
vue: true
}),
new HtmlWebpackPlugin({
filename: `index.${name}.html`,
template: 'src/index.html',
title: 'Project Name'
}),
new MiniCssExtractPlugin({ filename: 'app.css', hot: true }),
new VueLoaderPlugin()
]
};
}
Please add an alias to specify the exact .js module you'd like to import, like this for example:
resolve: {
extensions: ['.ts','.js'],
modules: ['node_modules'],
alias: {
'oidc-client': 'oidc-client-js/dist/oidc-client.rsa256.slim'
}
}
If you don't specify an alias, webpack/ will follow node module resolution and we'll eventually find your module by going to
library oidc-client-js in node_modules and follow package.json main property which is "lib/oidc-client.min.js" and that's not what you want.

Webpack 4 css modules TypeError: Cannot read property 'context' of undefined

I just upgraded to webpack 4. I use css modules.
ERROR:
ERROR in ./client/src/common/accordian-component/accordian.css
(./node_modules/css-loader??ref--5-1!./node_modules/postcss-loader/lib??ref--5-2!./client/src/common/accordian-component/accordian.css)
Module build failed: TypeError: Cannot read property 'context' of
undefined at Object.
(/Users/phillipjones/Workspace/sl_pathfinder/website/node_modules/css-loader/lib/loader.js:101:57)
at Array.map () at Object.
(/Users/phillipjones/Workspace/sl_pathfinder/website/node_modules/css-loader/lib/loader.js:99:31)
at
/Users/phillipjones/Workspace/sl_pathfinder/website/node_modules/css-loader/lib/processCss.js:200:3
From previous event: at Promise.then
(/Users/phillipjones/Workspace/sl_pathfinder/website/node_modules/cls-bluebird/lib/shimMethod.js:38:20) at Object.loader
(/Users/phillipjones/Workspace/sl_pathfinder/website/node_modules/postcss-loader/lib/index.js:96:6)
# ./client/src/common/accordian-component/accordian.css 2:14-160
21:1-42:3 21:158-42:2 22:19-165 #
./client/src/common/accordian-component/accordian-item.jsx #
./client/src/common/accordian-component/all-components.js #
./client/src/common/accordian-component/accordian-component.jsx #
./client/src/common/index.js #
./client/src/views/main-view/all-components.js #
./client/src/views/main-view/main-view.jsx #
./client/src/views/index.js # ./client/src/routes/index.jsx #
./client/src/App.jsx # multi ./client/src/App.jsx
webpack.config.js
require('dotenv').config();
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const importPlugin = require('postcss-import');
const postcssFunctions = require('postcss-functions')({
functions: require('./postcss-functions') }); // eslint-disable-line
// const fs = require('fs');
// const ExtractTextPlugin = require('extract-text-webpack-plugin');
const nodeEnv = process.env.NODE_ENV || 'development';
// console.log({ nodeEnv });
let mode = 'production';
if (nodeEnv !== 'production') {
mode = 'development';
}
// const api_base_url = process.env.API_BASE_URL || 'http://localhost:8000/api';
// Common rules
const rules = [
{
test: /\.jsx?$/,
use: ['babel-loader'],
include: /(pathfinder-common|src)/,
},
{
test: /\.css$/i,
include: /client/,
use: [
'style-loader',
{ loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
importLoaders: 1,
camelCase: true,
localIdentName: '[name]__[local]___[hash:base64:5]',
},
},
{
loader: 'postcss-loader',
options: {
plugins: [
importPlugin(),
autoprefixer({ browsers: ['last 2 versions'] }),
postcssFunctions,
],
},
},
],
},
{
test: /\.woff2?/,
loader: 'url-loader',
options: {
name: '[path][name].[ext]?[hash]',
mimetype: 'application/font-woff',
},
},
{
test: /\.(jpe?g|gif|svg|ico|ttf|otf|woff|woff2)(\?[a-z0-9=&.]+)?$/i,
loader: 'url-loader',
options: {
name: '[path][name].[ext]?[hash]',
},
},
{
test: /\.png$/,
loader: 'url-loader?mimetype=image/png',
options: {
name: '[path][name].[ext]?[hash]',
},
},
];
module.exports = {
mode,
context: __dirname,
devtool: 'cheap-module-source-map',
entry: ['./client/src/App.jsx'],
output: {
path: path.resolve(__dirname, './client/public'),
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
modules: [path.resolve(__dirname, 'node_modules')],
symlinks: true,
},
plugins: [
// new ExtractTextPlugin('ml-common.css'),
new webpack.optimize.OccurrenceOrderPlugin(),
// new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({ 'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV) } }),
],
module: {
rules,
},
devServer: {
contentBase: path.resolve(__dirname, './client/public'),
hot: true,
quiet: false,
noInfo: false,
publicPath: 'http://localhost:8000',
overlay: {
warnings: true,
errors: true,
},
},
};
upgraded the css-loader and it worked
"css-loader": "^0.28.11",

Webpack require.ensure Error on --optimize--minimize

I need to do code splitting and load some React component and other script on-demand, I simply do it like:
<Route path="/journal" getComponent={function (nextState, cb) {
require.ensure([], function (require) {
cb(null, require("./components/Journal"));
})
}} />
In development, just run webpack it works just fine.
But for production build, I run webpack -p, then I always get error:
Uncaught TypeError: Cannot read property 'call' of undefined
at e (bootstrap a99e046…:50)
line 50 is:
// Execute the module function
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
What could be the issue ?
My webpack config:
var webpack = require('webpack');
var merge = require('webpack-merge');
var validate = require('webpack-validator');
var parts = require('./webpack.parts');
var common = {
entry: {
vendor: ['react', 'react-dom', 'lodash'],
},
output: {
filename: "index.bundle.js",
path: __dirname + '/public/js/',
publicPath: __dirname + '/public/js/'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: 3,
filename: "vendor.bundle.js"
})
]
};
var config;
switch(process.env.npm_lifecycle_event) {
case 'build':
config = merge(common,
{
devtool: 'source-map',
entry: {
app: [ __dirname + '/src/index.js']
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loaders: ["babel-loader"]}
]
}
},
parts.productionOptimize()
);
break;
default:
config = merge(
common,
{
devtool: 'eval-source-map',
entry: {
app: ['webpack-hot-middleware/client', __dirname + '/src/index.js']
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loaders: ["react-hot","babel-loader"]}
]
}
},
parts.devServer({
host: process.env.HOST,
port: process.env.PORT
})
);
}
module.exports = validate(config);
webpack.parts.js
var webpack = require('webpack');
exports.devServer = function(options) {
return {
devServer: {
historyApiFallback: true,
inline: true,
hot: true,
stats: 'errors-only',
host: options.host,
port: options.port
},
plugins: [
new webpack.HotModuleReplacementPlugin({
multistep: true
})
]
};
}
exports.productionOptimize = function () {
return {
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin()
]
}
}
I did it wrong, publicPath should not be absolute:
I change
publicPath: __dirname + '/public/js/'
to
publicPath: '/js/'

How to handle static assets with webpack server side?

I'm trying to create an universal react app (using webpack both on server and on the client) and struggle with images import. I want to write this :
import someImage from './someImage.png'
const SomeImage = () => <img src={someImage}/>
Here's my webpack config file:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./client',
'babel-polyfill'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
modulesDirectories: ['node_modules', 'shared'],
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel']
},
{
test: /\.css/,
exclude: /node_modules/,
loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]')
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?emitFile=false',
]
}
]
},
plugins: [
new ExtractTextPlugin('styles.css', { allChunks: true }),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
devtool: 'inline-source-map',
devServer: {
hot: true,
proxy: {
'*': 'http://127.0.0.1:' + (process.env.PORT || 3000)
},
host: '127.0.0.1'
}
};
Obviously it's not working server side because node try to read the content of the ./someImage.png file, resulting in an error.
How can I handle this ? I know there are packages such as webpack-isomorphic-tools or universal-webpack or even the file-loader package that can emit or not the file, but I don't understand of to use it in my universal app.
I'm using file-loader with emitFile: false to exclude assets from bundling on server side. Works as expected.
const imageRules = (emit = true) => ({
test: /\.(png|svg|jpeg|jpg|gif|ico)$/,
type: "asset",
generator: {
emit: emit,
},
});
Then use it in webpack client config:
module: {
rules: [imageRules()],
},
And in server config
module: {
rules: [imageRules(false)],
},

Categories