I need help here.
I am bundling a custom library (named for the example LibraryJS and it uses lodash as dependency.
In the webpack configuration I setup lodash as an external dependency like so:
{
externals: {
"lodash"
}
}
It works great.
But then when I want to use this library inside another project, I got the following error: "libraryjs.js:77 Uncaught ReferenceError: lodash is not defined"
which is the following line:
/***/ }),
/* 1 */
/***/ (function(module, exports) {
=> module.exports = lodash;
/***/ }),
The fact is, I am using lodash as well in my project, so it should be working.
What am I doing wrong?
By the way, I am using gulp + browserify to bundle my project and gulp + gulp-webpack to bundle the library.
Edit: I found a way to fix the error, but I really don't want to stick with this fix because it's really... ugly... See bellow:
const lodash = require('lodash')
window.lodash = lodash; // <= The fix, ugh
Thank you for the help!
I had a similar situation trying to build a library - this is the solution I found.
Goal:
Build a library that depends on Lodash without including Lodash in that library bundle.
The consumer of the library is responsible for making Lodash available to our library.
I used the Authoring Libraries section of the documentation to put together this solution.
Specifically these two sections:
Externalize Lodash
Expose the Library
There is an example project showing this configuration as well:
https://github.com/webpack/webpack/tree/master/examples/externals
Solution:
1. Bundle our library, excluding lodash
// "my-lib" package.json
{
"name": "my-lib",
"version": "0.5.0",
"main": "my-lib.js",
"peerDependencies": {
"lodash": "^4.17.5"
},
"devDependencies": {
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14"
}
}
Here's our example library that imports lodash and uses it. Note that whilst we depend on lodash, it won't be included in our bundle.
// lib-entry.js
import _ from "lodash";
export default function doubleUp(listOfNum){
// Do something using lodash
let result = _.flatMap(listOfNum, (i) => [i, i]);
return result;
}
Here's our webpack.config.js that bundles our library, but excludes lodash from the bundle:
// "my-lib" webpack.config.js
module.exports = {
entry: {
'my-lib': './lib-entry.ts',
},
output: {
filename: '[name].js',
// [1]
libraryTarget: 'umd',
/*
[2]
NOTE: until this issue is fixed: https://github.com/webpack/webpack/issues/6525
we need to define `globalObject` in Webpack 4 to correctly build a universal library
(i.e. node and browser compatible).
*/
globalObject: 'this',
},
externals: {
// [3]
'lodash': {
commonjs: 'lodash',
commonjs2: 'lodash',
amd: 'lodash',
root: '_',
},
},
resolve: {
extensions: ['.js'],
},
};
[1] This tells Webpack to bundle our library for different environments (so it will work when loaded via: browser scripts, Node CommonJS, AMD, and downstream Webpack projects). NOTE: This is needed otherwise the externals config in [3] will output an incorrect undefined module in your bundle.
[2] Workaround for a Webpack 4 bug (if you're in the future then check if this is still relevant and needed). Also described here: https://stackoverflow.com/a/49119917/81723
[3] From the documentation: "set the externals option to define dependencies that should be resolved in the target environment". We're telling Webpack to exclude lodash from the library bundle and that consumers of our library are responsible for providing it.
2. Use the library in a downstream application
Define an application that depends on our my-lib library:
// "my-app" package.json
{
"name": "my-app",
"version": "1.0.0",
"dependencies": {
"lodash": "^4.17.5",
"my-lib": "^0.5.0"
},
"devDependencies": {
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14"
}
}
Our application imports lodash into its environment (because our library needs it) and then use our library:
// app-entry.js
import _ from "lodash";
import doubleUp from "my-lib";
let result = doubleUp([1, 2, 3]);
console.log(result); // [1, 1, 2, 2, 3, 3]
Here's the webpack.config.js for our application:
// "my-app" webpack.config.js
const path = require('path');
module.exports = {
entry: {
'my-app': './app-entry.ts',
},
output: {
filename: '[name].js',
},
resolve: {
extensions: ['.js'],
alias: {
/*
[1]
Resolve all `lodash` requests to the same location otherwise
we end up with two versions loaded into the bundle, one
for `my-lib` and one for `my-app`.
*/
lodash: path.resolve('./node_modules/lodash/index.js'),
}
},
};
[1] This alias config means anytime Webpack encounters require('lodash') or import ... from "lodash"; it will resolve it to this one module on disk. I found I had to do this to avoid getting multiple versions of lodash loaded into my bundle. Webpack was including one version for my-app and one for my-lib, but this fixes it so that both get the same version.
Related
Project setup:
Vuejs 3
Webpack 4
Babel
TS
We created the project using vue-cli and add the dependency to the library.
We then imported a project (Vue Currency Input v2.0.0) that uses optional chaining. But we get the following error while executing the serve script:
error in ./node_modules/vue-currency-input/dist/index.esm.js
Module parse failed: Unexpected token (265:36)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| getMinValue() {
| let min = this.toFloat(-Number.MAX_SAFE_INTEGER);
> if (this.options.valueRange?.min !== undefined) {
| min = Math.max(this.options.valueRange?.min, this.toFloat(-Number.MAX_SAFE_INTEGER));
| }
I read that Webpack 4 doesn't support optional chaining by default. So, we added the Babel plugin for optional chaining. This is our babel.config.js file:
module.exports = {
presets: ["#vue/cli-plugin-babel/preset"],
plugins: ["#babel/plugin-proposal-optional-chaining"],
};
(But, if I am correct, this plugin is now enable by default in the babel-preset. So this modification might be useless ^^)
One thing that I don't understand is that we can use optional chaining in the .vue files.
I created a SandBox with all the files: SandBox
How could I solve this error?
I was able to overcome this issue using #babel/plugin-proposal-optional-chaining, but for me the only way I could get Webpack to use the Babel plugin was to shove the babel-loader configuration through the Webpack options in vue.config.js. Here is a minimal vue.config.js:
const path = require('path');
module.exports = {
chainWebpack: config => {
config.module
.rule('supportChaining')
.test(/\.js$/)
.include
.add(path.resolve('node_modules/PROBLEM_MODULE'))
.end()
.use('babel-loader')
.loader('babel-loader')
.tap(options => ({ ...options,
plugins : ['#babel/plugin-proposal-optional-chaining']
}))
.end()
}
};
NB replace "PROBLEM_MODULE" in the above with the module where you have the problem.
Surprisingly I did not need to install #babel/plugin-proposal-optional-chaining with NPM. I did a go/no-go test with an app scaffolded with #vue/cli 4.5.13, in my case without typescript. I imported the NPM module that has been causing my grief (#vime/vue-next 5.0.31 BTW), ran the serve script and got the Unexpected token error on a line containing optional chaining. I then plunked the above vue.config.js into the project root and ran the serve script again, this time with no errors.
My point is it appears this problem can be addressed without polluting one's development environment very much.
The Vue forums are in denial about this problem, claiming Vue 3 supports optional chaining. Apparently not, however, in node modules. A post in this thread by atflick on 2/26/2021 was a big help.
Had same issue with Vue 2 without typescript.
To fix this you need to force babel preset to include optional chaining rule:
presets: [
[
'#vue/cli-plugin-babel/preset',
{
include: ['#babel/plugin-proposal-optional-chaining'],
},
],
],
Can also be achieved by setting old browser target in browserslist config.
Most importantly, you need to add your failing module to transpileDependencies in vue.config.js:
module.exports = {
...
transpileDependencies: ['vue-currency-input],
}
This is required, because babel by default will exclude all node_modules from transpilation (mentioned in vue cli docs), thus no configured plugins will be applied.
I had a similar problem. I'm using nuxt but my .babelrc file looks like the below, and got it working for me.
{
"presets": [
["#babel/preset-env"]
],
"plugins":[
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
],
"env": {
"test": {
"plugins": [
["transform-regenerator", {
"regenerator": true
}],
"#babel/plugin-transform-runtime"
],
"presets": [
["#babel/preset-env", {
"useBuiltIns": false
}]
]
}
}
}
I managed to fix the solution by adding these lines to package.json:
...
"scripts": {
"preinstall": "npx npm-force-resolutions",
...
},
"resolutions": {
"acorn": "8.0.1"
},
...
I have project which uses lerna ( monorepo, multiple packages ). Few of the packages are standalone apps.
What I want to achieve is having aliases on few of the packages to have something like dependency injection. So for example I have alias #package1/backendProvider/useCheckout and in webpack in my standalone app I resolve it as ../../API/REST/useCheckout . So when I change backend provider to something else I would only change it in webpack.
Problem
Problem appears when this alias is used by some other package ( not standalone app ). For example:
Directory structure looks like this:
Project
packageA
ComponentA
packageB
API
REST
useCheckout
standalone app
ComponentA is in packageA
useCheckout is in packageB under /API/REST/useCheckout path
ComponentA uses useCheckout with alias like import useCheckout from '#packageA/backendProvider/useCheckout
Standalone app uses componentA
The error I get is that Module not found: Can't resolve '#packageA/backendProvider/useCheckout
However when same alias is used in standalone app ( that has webpack with config provided below ) it is working. Problem occurs only for dependencies.
Potential solutions
I know that one solution would be to compile each package with webpack - but that doesn't really seem friendly. What I think is doable is to tell webpack to resolve those aliases to directory paths and then to recompile it. First part ( resolving aliases ) is done.
Current code
As I'm using NextJS my webpack config looks like this:
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
// Fixes npm packages that depend on `fs` module
config.node = {
fs: "empty"
};
const aliases = {
...
"#package1/backendProvider": "../../API/REST/"
};
Object.keys(aliases).forEach(alias => {
config.module.rules.push({
test: /\.(js|jsx)$/,
include: [path.resolve(__dirname, aliases[alias])],
use: [defaultLoaders.babel]
});
config.resolve.alias[alias] = path.resolve(__dirname, aliases[alias]);
});
return config;
}
You don’t need to use aliases. I have a similar setup, just switch to yarn (v1) workspaces which does a pretty smart trick, it adds sym link to all of your packages in the root node_modules.
This way, each package can import other packages without any issue.
In order to apply yarn workspaces with lerna:
// lerna.json
{
"npmClient": "yarn",
"useWorkspaces": true,
"packages": [
"packages/**"
],
}
// package.json
{
...
"private": true,
"workspaces": [
"packages/*",
]
...
}
This will enable yarn workspace with lerna.
The only think that remains to solve is to make consumer package to transpile the required package (since default configs of babel & webpack is to ignore node_module transpilation).
In Next.js project it is easy, use next-transpile-modules.
// next.config.js
const withTM = require('next-transpile-modules')(['somemodule', 'and-another']); // pass the modules you would like to see transpiled
module.exports = withTM();
In other packages that are using webpack you will need to instruct webpack to transpile your consumed packages (lets assume that they are under npm scope of #somescope/).
So for example, in order to transpile typescript, you can add additional module loader.
// webpack.config.js
{
...
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
include: /[\\/]node_modules[\\/]#somescope[\\/]/, // <-- instruct to transpile ts files from this path
options: {
allowTsInNodeModules: true, // <- this a specific option of ts-loader
transpileOnly: isDevelopment,
compilerOptions: {
module: 'commonjs',
noEmit: false,
},
},
}
]
}
...
resolve: {
symlinks: false, // <-- important
}
}
If you have css, you will need add a section for css as well.
Hope this helps.
Bonus advantage, yarn workspaces will reduce your node_modules size since it will install duplicate packages (with the same semver version) once!
I have a project in which I bundle a components library using Rollup (generating a bundle.esm.js file). These components are then used in another project, that generates web pages which use these components - each page is using different components.
The problem is, that the entire components library is always bundled with the different page bundles, regardless of which components I'm using, unnecessarily increasing the bundle size.
This is my Rollup setup:
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';
const extensions = [
'.js', '.jsx', '.ts', '.tsx',
];
export default [
{
input: './src/base/index.ts',
plugins: [
peerDepsExternal(),
resolve({ extensions }),
babel({
exclude: 'node_modules/**',
extensions,
}),
commonjs(),
],
output: [
{ file: pkg.main, format: 'cjs', sourcemap: true },
{ file: pkg.module, format: 'es', sourcemap: true },
],
watch: {
clearScreen: false,
},
},
];
I have "modules" set to false in webpack, as well.
There are things you will need to do to achieve treeshakable code from both sides - the built package and the project using it.
From your code snippet, I see that you have not add flag preserveModules: true in the rollup config file to prevent the build output from bundling. Webpack can not treeshake a bundled file FYI.
export default {
...
preserveModules: true,
...
}
On the side of the project that using it, you have to specify sideEffects in the package.json - read the doc to know how to config them. Beside that, the optimization in webpack has to has sideEffects: true, also read the doc here.
Hope this helps!
As you don't know which components of your Component Library (CL) will be needed by the adopters repositories you need to export everything but in a way
the adopters can execute a tree-shaking on your CL when they do their own build (and just include what they really need).
In a few words, you have to make your CL, tree-shakable. In order to achieve this, on your CL repo you have to:
Use bundlers that support tree-shaking (rollup, webpack, etc..)
Create the build for modules of type es/esm, NOT commonJS/cjs, etc..
Ensure no transpilers/compilers (babel,tsconfig, etc..) usually used as plugins, transform your ES module syntax to another module syntax.
By the default, the behavior of the popular Babel preset #babel/preset-env may break this rule, see the documentation for more details.
// babelrc.json example that worked for me
[
"#babel/preset-env",
{
"targets": ">0.2%, not dead, not op_mini all"
}
],
In the codebase, you always have to use import/export (no require) syntax, and import specifically the things you need only.
import arrayUtils from "array-utils"; //WRONG
import { unique, implode, explode } from "array-utils"; //OK
Configure your sideEffects on the package.json.
"sideEffects": ["**/*.css"], //example 1
"sideEffects": false, //example 2
DO NOT create a single-bundle file but keep the files separated after your build process (official docs don't say this but was the only solution that worked for me)
// rollup.config.js example
const config = [
{
input: 'src/index.ts',
output: [
{
format: 'esm', // set ES modules
dir: 'lib', // indicate not create a single-file
preserveModules: true, // indicate not create a single-file
preserveModulesRoot: 'src', // optional but useful to create a more plain folder structure
sourcemap: true, //optional
},
],
... }]
Additionally, you may need to change your module entry point in order the adopters can directly access to the proper index.js file where you are exporting everthing:
// package.json example
{
...
"module": "lib/index.js", //set the entrypoint file
}
Note: Remember that tree-shaking is executed by an adopter repository that has a build process that supports tree-shaking (eg: a CRA repo) and usually tree-shaking is just executed on prod mode (npm run build), no on dev mode. So be sure to properly test if this is working or not.
I'm using node.js and webpack to create a bundle. From what I've read, node.js should contain fs module for managing files. However when I call require("fs") I get an Cannot find module "fs" error. What should I do?
I came across this problem myself when bundling with webpack and found the answer on this thread.
The way to solve it for me was to use the following config:
module.exports = {
entry: "./app",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: 'node_modules',
loader: 'babel',
query: {presets: ['es2015']},
}
]
},
target: 'node'
};
By setting target to node webpack will make the necessary changes to bundle your node application
Edit: This answer targeted webpack 1.x which has now been superseded.
If you are running your webpack bundle in nodejs environment then target: 'node' is required in webpack.config.js file otherwise webpack takes default value as web for target check here.
You can resolve the issue in two ways
Add below configuration to your webpack.config.js
node: {
fs: "empty"
}
OR
Add below configuration to your package.json
"browser": {
"fs": false
}
Edit:
promising fix is
"browser": {
"fs": false
}
I had the same issue when bundling a NWjs application using webworkers (which in turn had node enabled).
The solution I found was to include each native module I used in externals with the prefix commonjs to the name of the module. For example:
...
target: "webworker", // or 'node' or 'node-webkit'
externals:{
fs: "commonjs fs",
path: "commonjs path"
}
...
I've done the same for targets "webworker" and "node-webkit" in different projects to solve the same issue.
webpack nwjs webworker nodejs node
Add below configuration to your webpack.config.js
resolve: {
fallback: {
fs: false
}
}
I needed to build a class that would use fetch if executed in a browser, or fs if executed in node. For other reasons, it was impractical to produce separate bundles, so I produced a single browser-targeted bundle.
The solution I used was to use eval('require("fs")') if the script was running in node.
const fs = eval('require("fs")')
Browser-safe (fs is null in the browser):
const fs = typeof window === 'object'
? null
: eval('require("fs")')
After trying everything I found on the internet (target, externals, node configs), the only solution that actually worked for me was replacing:
const filesystem = require("fs")
or
import fs from "fs"
by the special webpack version
const fs = __non_webpack_require__("fs")
This generates a require function that is not parsed by webpack.
In addition to the answer of PDG
I'm used to this short copy/paste candy.
Using path and fs :
var nodeModules = {};
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
.filter(x => ['.bin'].indexOf(x) === -1)
.forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });
// Before your webpack configuration
module.exports = {
...
}
Then inside your configuration file, include the nodeModules variable in the externals
...
externals: nodeModules,
...
It would be more elegant to use pre-defined solution as:
Adding target: 'node' to webpack config file.
More info on: official documentation
For the solution we are building we had to force an older version of webpack:
npm install --save --force webpack#webpack-3
We have built a Nuxt/VueJS project.
Nuxt has its own config file called nuxt.config.js within which we configure webpack and other build setup.
In our package.json, we have included the lodash package.
In our code, we have been careful to load only import what we require, for example:
import orderBy from 'lodash/orderBy'
In nuxt.config.js, lodash is add to the vendor list.
However when we create the build, webpack always includes the entire lodash library instead of including only what we have used in our code.
I have read numerous tutorials but haven't got the answer. Some of those answers will surely work if it was a webpack only project. But in our case, it is through nuxt config file.
Looking forward to some help.
Below is the partial nuxt.config.js file. Only relevant/important parts are included:
const resolve = require('resolve')
const webpack = require('webpack')
module.exports = {
/*
** Headers of the page
*/
head: {
},
modules: [
['#nuxtjs/component-cache', { maxAge: 1000 * 60 * 10 }]
],
plugins: [
{ src: '~/plugins/intersection', ssr: false },
],
build: {
vendor: ['moment', 'lodash'],
analyze: {
analyzerMode: 'static'
},
postcss: {
plugins: {
'postcss-custom-properties': false
}
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
/*
** Run ESLINT on save
*/
extend (config, ctx) {
// config.resolve.alias['create-api'] = `./create-api-${ctx.isClient ? 'client' : 'server'}.js`
}
}
}
You can npm install only the required packages
Lodash can be split up per custom builds. You can find a list of already available ones here. You can use them like this: npm i -S lodash.orderby. I didn't check it but you would probably also need to change import orderBy from 'lodash/orderBy' to import orderBy from 'lodash.orderby'.