Webpack plugin: how to read files of plugin consumer at build time? - npm

Is it possible to read the contents of the repo which installed my Webpack plugin?
Essentially, I've written a particular JS library which requires the caller to use require.context in their application code to read some files at build time and pass them to the library:
import Library from 'library';
new Library({
requires: require.context('./foo', false, /\w+\.js$/),
});
I would like to take the burden off of the user and just make that require.context call inside the library to simplify the API to this:
import Library from 'library';
new Library();
However, it doesn't work because the library has no knowledge of when the application code's Webpack build ran.
I've tried writing a Webpack plugin inside the library:
const path = require('path');
class TestPlugin {
apply(compiler) {
compiler.hooks.beforeRun.tap('TestPlugin', () => {
console.log(
`Path where webpack was executed: ${compiler.options.context}`
);
});
}
}
module.exports = {
...
plugins: [new TestPlugin()],
};
However, this only gets called when the library itself is built not when the application is built.
How can I move the require.context call into the library (which is an NPM dependency) and still have it read the caller's files?

Related

How to bundle tailwind css inside a Vue Component Package

In one of my projects, I build a nice vue3 component that could be useful to several other projects. So I decided to publish it as an NPM package and share it with everyone.
I wrote the isolate component, build it and publish BUT I use Tailwind css to make the style.
When I publish and install the component everything is working BUT without the beauty of the css part.
I tried several configurations and alternative tools to generate the package that automatically add the tailwind as an inner dependency to my package.
Does someone have experience with this? how can build/bundle my component by adding the tailwind CSS instructions into it?
You're almost there
Since you've got your component working, the majority of the part has been done.
For configuring the styling of the component you need to identify the Tailwind CSS classes being used by your Vue component package and retain them in the final CSS that is generated by the Tailwind engine in your project.
Follow below steps in the project where you want to use your tailwind vue component package.
For Tailwind CSS V3
// tailwind.config.js
module.exports = [
//...
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/package-name/**/*.{vue,js,ts,jsx,tsx}" // Add this line
// Replace "package-name" with the name of the dependency package
],
//...
]
For Tailwind CSS V2
// tailwind.config.js
module.exports = [
//...
purge: {
//...
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/package-name/**/*.{vue,js,ts,jsx,tsx}" // Add this line
// Replace "package-name" with the name of the dependency package
],
//...
//...
}
]
The content property in the tailwind.config.js file defines file path pattern that the tailwind engine should look into, for generating the final CSS file.
For Pro users
You may also try to automate the above setup by writing an install script for your npm package to add this configuration to the tailwind.config.js file
References
Tailwind Docs - 3rd party integration
It's a bit difficult for someone to answer your question as you've not really shared the source code, but thankfully (and a bit incorrectly), you've published the src directory to npm.
The core issue here is that when you're building a component library, you are running npm run build:npm which translates to vue-cli-service build --target lib --name getjvNumPad src/index.js.
The index.js reads as follows:
import component from './components/numeric-pad.vue'
// Declare install function executed by Vue.use()
export function install (Vue) {
if (install.installed) return
install.installed = true
Vue.component('getjv-num-pad', component)
}
// Create module definition for Vue.use()
const plugin = {
install
}
// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null
if (typeof window !== 'undefined') {
GlobalVue = window.Vue
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue
}
if (GlobalVue) {
GlobalVue.use(plugin)
}
// To allow use as module (npm/webpack/etc.) export component
export default component
There is no mention of importing any CSS, hence no CSS included in the built version.
The simplest solution would be to include the index.css import in your index.js or the src/components/numeric-pad.vue file under the <style> section.
Lastly, I'm a bit rusty on how components are built, but you might find that Vue outputs the CSS as a separate file. In that case, you would also need to update your package.json to include an exports field.

How to create a library with dynamic imports which can be imported by Nuxt?

I am trying to reuse Nuxt.js components from one project in another project. So I created a new project which imports the components needed and then exports them as a npm package.
npm package (main.js)
import SomeComponent from '../foobar/SomeComponent.vue'
export default {
install (Vue) {
Vue.component(SomeComponent)
}
}
export {
SomeComponent
}
npm package (webpack.config.js)
module.exports = {
entry: path.resolve(__dirname + '/src/main.js'),
output: {
path: path.resolve(__dirname + '/dist/'),
chunkFilename: '[name].build.js',
filename: 'build.js',
libraryTarget: 'umd',
libraryExport: 'default',
library: 'MyLibrary',
umdNamedDefine: true
}
}
Then in my new Nuxt.js project I can simply import the npm package and the components will be installed automatically. While this works fine when not using any code splitting it will throw an error when trying to use dynamic imports in the SomeComponent.vue file.
When adding dynamic imports in my component like so import(/* webpackChunkName: "mapbox" */ 'mapbox-gl') the chunks will be created but when running Nuxt in development mode I always get the error:
Uncaught (in promise) ChunkLoadError: Loading chunk 1 failed.
Nuxt does not find the created chunk files. I tried playing around with publicPath but I don't get what path would be the right one for Nuxt to be able to access them?

Bundle size is big, how to reduce size of app.js?

I am using Vue.js and have only 4 components in my project.
I imported only bootstrap, jquery and lodash:
import { map } from 'lodash';
import 'bootstrap/js/dist/modal';
import $ from "jquery";
But npm run production creates
bundle of 400kb size.
npm run production is configured as shown below.
cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
Is it possible to reduce bundle size to ~100KB ? If yes how?
You should add bundle analyzer to your webpack config.
That tool will help you to understand what is going on with your final bundle for example:
you have imported something accidentally and didn't noticed that
one of your dependencies is really big and you should avoid using it
you accidentally imported whole library when you just wanted to import single function from that library (that is common with lodash)
Here is an example of how you can add bundle analyzer to your webpack config:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const isBundleAnalyze = true; // turn it too true only when you want to analyze your bundle, should be false by default
module.exports = {
// ... rest webpack config here
plugins: [
// ... rest webpack plugins here
...isBundleAnalyze ? [ new BundleAnalyzerPlugin() ] : []
]
};
Also check your final js file.
It should be a single line of code with simple variables. Something like this: !function(e){function t(t){for(var n,r,o=t[0],i=t[1],s=0,l=[];s<o.length;s++) if it doesn't looks like that it means that you configured your production webpack build incorrectly.
It's pretty obvious why your bundle is over 400kb, you are importing lodash and jquery, you are just missing moment.js (a little joke), but one thing that you can do is use only what you need.
First, if you are using Vue, or React, or any of those jQuery UI libraries you shouldn't be using jQuery unless is necessary.
Another thing that you can do is import only what you need, instead of:
import { map } from 'lodash';
try
import map from 'lodash/map';
or even better
import map from 'lodash.map';
https://www.npmjs.com/package/lodash.map
Lazy imports, read more here. This will allow splitting your bundle into pieces that can be called at execution time, reducing considerably your app size.
const Foo = () => import('./Foo.vue')
There is also SSR (Server Side Rendering), which is basically generating the initial HTML code of your app at build time and rendering outputting that, to show the users that something is on the site, but you also need to understand that, this won't do much, since the browser needs to parse the Javascript code (the hydration process) in order to make the site functional.
If you are using React as of April 2021, the React team announced React Server Components, which seems like a big thing coming up, I supposed that many other libraries will be moving components to the server (and I hope Vue does).
Again as of today don't use it on production.
Other answers mentioned the use of webpack-bundle-analyzer, here is a trick how to use it:
webpack.config.js
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const analyzing = process.env.NODE_ENV === 'analyze';
module.exports = {
plugin: [
...(analyzing ? [new BundleAnalyzerPlugin()] : [])
]
}
on your package.json
{
"scripts": {
"analyze": "NODE_ENV=analyze webpack build"
}
}
use CompressionWebpackPlugin and try gzip

how to override vue cli-service entry settings

I'm trying to integrate a vue project that I built with the vue cli into an existing .net app. I'm very new to vue, so I'm trying to follow guides and such, but am left with lots of questions.
While trying to compile this, I found that the vue cli-service node module has the following for setting the main.js file located in it's base.js file.
webpackConfig
.mode('development')
.context(api.service.context)
.entry('app')
.add('./src/main.js')
.end()
.output
.path(api.resolve(options.outputDir))
.filename(isLegacyBundle ? '[name]-legacy.js' : '[name].js')
.publicPath(options.publicPath)
I need to override this since my .net app doesn't have a src directory and the usage of this vue app won't follow that path structure. I'm not seeing a way to do it in my vue.config.js file. I would expect that if I can override it, that would be the spot.
I could overwrite the base.js file where this exists, but when a co-worker runs npm install, they would get the default value rather than what I have. The only option I see there is checking in all the node modules to git which we really don't want to do.
For anyone in a similar situation, I found what worked for me. It's not the ideal solution due to the fact that it forces you to build into a js folder. That resulted in the file being put in Scripts\build\vue\js. Would be nice to be able to just dump it in the vue folder, but at least this works. Code below.
vue.config.js
module.exports = {
publicPath : "/",
outputDir: "Scripts/build/vue", //where to put the files
// Modify Webpack config
// https://cli.vuejs.org/config/#chainwebpack
chainWebpack: config => {
// Not naming bundle 'app'
config.entryPoints.delete('app'); //removes what base.js added
},
// Overriding webpack config
configureWebpack: {
// Naming bundle 'bundleName'
entry: {
quote: './Scripts/Quote/index.js' //where to get the main vue app js file
},
optimization: {
splitChunks: false
}
},
filenameHashing: false,
pages: {
quoteApp: { //by using pages, it allowed me to name the output file quoteApp.js
entry: './Scripts/Quote/index.js',
filename: 'index.html'
}
}
}

pass environment variables during babel build phase for importing different files

I'm building a web (react with webpack & babel) and mobile apps (react-native with expo) for a project. I therefore created a common library for business logic and redux/api library.
Some code will be slightly different between web and mobile. In my case it's localStorage vs AsyncStorage, which I use for authentication among other things...
I'm trying to pass an environment variable for the build stage to switch import of certain files so that the correct file is loaded for each build which are simply path linked (ie no pre-build of my library, I just do import '../mylib') ex:
if(PLATFORM === 'mobile'){
import StorageModule from './mobile-storage-module`
} else {
import StorageModule from './mobile-storage-module`
}
export default StorageModule
Try 1
#babel/preset-env to say if it's mobile or web so that it imports different libraries depending on build like so:
My .babelrc has this:
{
"presets": [
[
"#babel/preset-env",
{
"platform": "mobile"
}
]
]
}
And then in local storage file I do this:
export default () => {
const platform = process.env.platform
if (platform === 'mobile') {
return import './storage-modules/storage-mobile'
}
return import './storage-modules/storage-web'
}
That didn't work, and this also didn't work for me.
Try 2
I installed react-native-dotenv and created a .env file with:
PLATFORM=mobile
And set the plugin in my .babelrc:
{
"presets": [
"babel-preset-expo",
"react-native-dotenv"
]
}
And in my example file, I tried this:
import { PLATFORM } from 'react-native-dotenv'
export default PLATFORM === 'mobile' ? import './storage-modules/storage-mobile' : import './storage-modules/storage-web'
But now my build doesn't work. Any idea how I do dynamic imports during the build process that works for babel in react-native app and webpack build (also uses babel)?
First, #babel/preset-env does not do what you think it does. This is not for specifying your own variables, it is a plugin to automatically use the right target and pollyfills for the browsers you want to support.
The easiest way to get environment variables is with the webpack define plugin (which is part of webpack, so no need to install anything extra)
Just add this to your webpack config.
plugins: [
new webpack.DefinePlugin({
'process.env': {
platform: 'mobile',
},
}),
],
Next, you can't use normal import statements inside of ifs.
import gets resolved before any code runs, either on build by webpack, or in supported environments on script load.
To import something on runtime, you need to use dynamic imports.
Here is an example of how this could look like.
export default new Promise(async resolve => {
resolve(
process.env.platform === 'mobile'
? (await import('./mobile.js')).default
: (await import('./desktop.js')).default
);
});
You can now import from this file like you normally would, but be aware that the default export is a promise.
As your question's title says "during babel build phase", I assume you would like to make different builds for desktop and mobile (not one build for both and load the needed modules dynamically run-time). So I would go like this:
Define the run scripts in package.json for desktop and mobile:
"scripts": {
"devmobile": "cross-env NODE_ENV=development PLATFORM=mobile webpack --progress",
"dev": "cross-env NODE_ENV=development webpack --progress",
}
... or you can create two different webpack.config.js files for desktop and mobile builds but I think the above is easier...
Then npm run devmobile to build for mobile and npm run dev for desktop.
Since I'm on Windows I use the cross-env package but this is the recommended way to be OS independent.
Then I would use Webpack's NormalModuleReplacementPlugin:
(based on this exmaple)
In your webpack.config.js:
// defining the wanted platform for the build (comfing form the npm run script)
const targetPlatform = process.env.PLATFORM || 'desktop';
// then use the plugin like this
plugins: [
new webpack.NormalModuleReplacementPlugin(/(.*)-PLATFORM(\.*)/, function(resource) {
resource.request = resource.request.replace(/-PLATFORM/, `-${targetPlatform}`);
}),
]
...then if you have these two files:
./storage-modules/storage-mobile.js
./storage-modules/storage-desktop.js
import the needed one in your script like this:
import './storage-modules/storage-PLATFORM';
This way the generated build will only contain the needed file for the current PLATFORM used for the build process.
Another possible solution could be the ifdef-loader but I haven't tested it. Maybe worth to try, seems easy.
If you want one build though and import the needed module dynamically, you could do something like this in your app.js (or whatever):
// this needs to have defined when the app is running
const targetPlatform = process.env.PLATFORM || 'desktop';
import(
/* webpackChunkName: "[request]" */
`./storage-modules/storage-${targetPlatform}`
).then(storageModule => {
// use the loaded module
});
or:
(async () => {
const storageModule = await import(
/* webpackChunkName: "[request]" */
`./storage-modules/storage-${targetPlatform}`
);
// use the loaded module
})();
For this to work Babel has to be configured.
More on Webpack with dynamic imports here.
You can use transform-inline-environment-variablesto pass platform to babel
"build-mobile": "PLATFORM=mobile ...",
"build-app": "PLATFORM=app ...",