gulp: babelify runs without error, but doesn't transform my node modules - npm

I am:
bundling with browserify
transforming ES6 to ES5 with babel
minifying the ES5 with uglifyjs
Which previously worked. However recently I've been getting errors from uglifyjs complaining about ES6 syntax, as if babelify hasn't actually run:
gulp.task('js', function() {
// Browserify/bundle the JS.
browserify({
entries: './public/js/src/index.js',
insertGlobals : true,
fullPaths: true, // For discify
debug: ! isProduction
}).transform(babelify)
.bundle()
.pipe(source('index.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./public/js/dist'))
});
Why isn't transform(babelify) transforming the code?
Please give actual answers, rather than cut and pasted gulpfiles.

The issue was using npm modules: babel ignores npm modules by default. So if the modules are ES6, they'll still be in ES6 when uglify runs.
Upgrading babel and using the global option has fixed things:
gulp.task('js', function() {
browserify({
entries: './public/js/src/index.js',
insertGlobals : true,
fullPaths: true, // For discify
debug: ! isProduction
}).transform(babelify, {
presets: ['es2015'],
compact: false,
global: true
})
.bundle()
.pipe(source('index.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./public/js/dist'))
})
Another option is to put this in package.json in your private modules. Note the syntax is strange, and uses arrays rather than objects to match items to their options:
{
"browserify": {
"transform": [
[
"babelify",
{ "presets": ["es2015"] }
]
]
}
}
See the babelify docs for more information.

Related

Cannot find module '#/assets/<file-name-here>.svg'. #vue/cli Version: 4.2.3 and 4.3.1

General jist:
import Image from '#/assets/default-profile-picture.svg'
//ERROR: Cannot find module '#/assets/default-profile-picture.svg'.Vetur(2307)
I have spent the better part of today trying to find a solution to this. I know there are a lot of other posts like this one, but they are all outdated (all over a year old).
I've just generated a clean Vue CLI app, and still have the same issue.
I'm using Vue CLI Version 4.2.3, and just attempted using Vue CLI Version 4.3.1, but ran into the same issue.
I have checked that the file is in assets.
I have checked that the filename is spelled correctly.
I have a feeling this is a webpack issue, as require() would not work when called using typescript.
I have tried creating vue.config.js and manually setting the path for assets.
Project setup configuration:
Features: Babel, TS, Router, ESLint
not class-style syntax
Babel used alongside Typescript
No history mode for router
eslint with error prevention only
Lint on save
Configs placed in package.json.
Error in Component.vue
<script lang="ts">
import Vue from 'vue'
/* Cannot find module '#/assets/default-profile-picture.svg'.Vetur(2307) */
import Image from '#/assets/default-profile-picture.svg'
export default Vue.extend({
components: {
},
props: [
'employeeImage',
'employeeName',
'employeeAge',
'employeeSalary'
],
data () {
return {
marked: false,
result: [],
name: this.employeeName,
age: this.employeeAge,
salary: this.employeeSalary
}
},
computed: {
compClasses: function () {
return {
marked: this.marked
}
},
imageDefault: function () {
if (this.employeeImage === '') {
console.log('employee image empty: ' + this.employeeImage)
return '#/assets/default-profile-picture.svg'
} else {
console.log('employee image set: ' + this.employeeImage)
return this.employeeImage
}
}
}
})
</script>
Typescript Config
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"#/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"/src/**/*.*",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
What am I doing wrong?
Thanks in advance!
Please keep this in mind, that this answer is not a solution but more like a work-around for this issue by the time this question has been asked/answered for vue-svg-loader(#vue/cli Version: 4.2.3 and 4.3.1).
You can use absolute path instead of using # to reference the file when you want to import .vue components. Here is an example:
Instead of this:
Read more about this issue and any possible solutions on official repository for this issue on GitHub:
Typescript Cannot find module '#/assets/svg/register.svg?inline' #92
Typescript does not support svg files.
Create a svg.d.ts file in your project source folder with the following content:
declare module '*.svg';
and restart your editor

Vue components does not appear on IE11 (Laravel)

All my vue components cannot be rendered in IE11. After searching, it looks like the reason is that IE does not support ES6 and above.
So my attempt at the moment is use babel:
My .babelrc:
{
"presets": [
[
"#babel/preset-env",
{
"debug": true,
"modules": false,
"forceAllTransforms": true,
"useBuiltIns": "usage",
"targets": "last 1 version, > 1%",
"corejs": 3
}
]
]
}
And I am using laravel-mix to compile the asset:
const mix = require("laravel-mix")
mix.js("resources/js/app.js", "public/js/app.js")
.sass("resources/sass/app.scss", "public/css/app.css")
.options({
processCssUrls: false
});
The compilation was running ok, but my vue components are still not rendered.
Any pointers to solve the problem?
Thanks.
// SOLUTION: Convert ES6 to ES2015 using babel and laravel-mix
Try this.
Install babel polyfill
npm install --save #babel/polyfill or yarn add #babel/polyfill
Add the code import #babel/polyfill to src/main.js.
import '#babel/polyfill'
import Vue from 'vue'
// ...
Change the babel.config.js as follows:
module.exports = {
presets: [
[
'#vue/app',
{
'useBuiltIns': 'entry'
}
]
]
}
Create the vue.config.js file and create:
(Add existing settings if they already exist.)
const ansiRegex = require('ansi-regex')
module.exports = {
......(기존 설정이 있다면 다음에 추가)
transpileDependencies: [ansiRegex]
}
Note. Use es6-promise when using a promise pattern.

How to compile my npm lib with webpack andwhat config?

I am making a js that I aim to publish npm. It will be used on both web and node.
I read webpack doc and I use this following config. Bundled and minified, it produces a 20kb package, which, IMHO, is pretty big for what it does.
Should I bundle it with webpack that way ?
{
mode: 'production',
entry: {
mylib: './src/mylib_browser.ts', // same for node
"mylib.min": './src/mylib_browser.ts'
},
watch: true,
target: 'web', // node for node
devtool: 'source-map',
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name]_browser.js',
libraryTarget: 'umd',
library: 'MyLib',
umdNamedDefine: true
},
plugins: [
new UglifyJsPlugin({
sourceMap: true,
include: /\.min\.js$/,
})
],
};
And I have the same config for node.
Is it the right config to do it? How could I decrease size ?
Also, when I look at other npm package, a lot are just vanilla js. Should I just let the user of my npm package, package it as a normal dependency ?
Are you sure the minification is happening? You have UglifyJs only minifying already minified files, which seems wrong?
new UglifyJsPlugin({
sourceMap: true,
include: /\.min\.js$/, //<= remove this line
})
Also, when I look at other npm package, a lot are just vanilla js. Should I just let the user of my npm package, package it as a normal dependency ?
If your library will be packaged by consumers then I would distribute with both minified and unminified sources. This allows consumers to include the minified library via one of the npm CDNs (e.g. unpkg) when hacking around (e.g. jsfiddle) and the unminified when using the library as part of a bundled application, e.g. via webpack.
If your library is only meant for the Node environment then minification is generally considered unnecessary and even a burden should the consumer encounter a bug in your library and wish to debug it.

responsive-loader with nuxt.js

I want to integrate responsive-loader into my Nuxt.js project which runs in SPA mode. (Optional I want to add Vuetify Progressive Image support also).
It will be a static hosting with Netlify.
Versions:
"nuxt": "^2.3.4"
"responsive-loader": "^1.2.0"
"sharp": "^0.21.1"
I found some solutions how to do it (https://stackoverflow.com/a/51982357/8804871) but this is not working for me.
When I run npm run build
I get an error message: "TypeError: Cannot set property 'exclude' of undefined"
My build section looks the following:
build: {
transpile: [/^vuetify/],
plugins: [
new VuetifyLoaderPlugin()
],
extractCSS: true,
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient, isServer }) {
// Default block
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
if (isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vuetify/]
})
]
}
// Default block end
// here I tell webpack not to include jpgs and pngs
// as base64 as an inline image
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
/*
** Configure responsive-loader
*/
config.module.rules.push({
test: /\.(jpe?g|png)$/i,
loader: "responsive-loader",
options: {
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
});
}
}
The error is probably found in this section:
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
Like said I get this error message: "TypeError: Cannot set property 'exclude' of undefined".
I run this project along with vuetify. I also would like to enable the Progressive image support together with responsive loader. Does anybody know how to setup both rules together?
https://github.com/vuetifyjs/vuetify-loader#progressive-images
The easiest way to integrate responsive-loader into a Nuxt.js project is to use this module: https://www.npmjs.com/package/nuxt-responsive-loader
Disclaimer: I created the module
The problem with your config that it relies on rule.loader property but rule can be defined in use or oneOf config sections as well.
Another one problem is that nuxt internal config has several rules with url-loader(for images, videos, fonts ...).
In your case the rule, you tried to find, has use section and url-loader is defined there, that's why your find function found nothing and threw this error:
{
"test": /\.(png|jpe?g|gif|svg|webp)$/,
"use": [{
"loader": "url-loader",
"options": {
"limit": 1000,
"name": "img/[hash:7].[ext]"
}
}]
}
About responsive-loader, you should remove extensions you want to process with responsive-loader from url-loader rule to avoid unexpected behavior and conflicts, here is extend function working example:
extend(config, ctx) {
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/';
// find by reg ex string to not rely on rule structure
let urlRule = config.module.rules.find(r => r.test.toString() === imgTest);
// you can use also "oneOf" section and define both loaders there.
// removed images from url-loader test
urlRule.test = /\.(svg|webp)$/;
config.module.rules.push({
test: /\.(png|jpe?g|gif)$/,
loader: "responsive-loader",
options: {
// place generated images to the same place as url-loader
name: "img/[hash:7]-[width].[ext]",
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
})
}
Yes, it looks dirty, but I think it's only way for now to change some loader.
What about vuetify - I think both loaders will conflict with each other and probably the solution is to use single loader that will work with your images.
Hope it helps.
Update for Nuxt >= 2.4.0:
They modified the rules array please update the following line:
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/i';
Then the code should work normally again.

Karma, Browserify on React is failing on LESS

I'm learning how to use React, and in turn use Karma as the test runner. I'm running Karma with browserify / reactify (mocha+kai). Whenever I run npm test, I get the following error:
ERROR [framework.browserify]: bundle error
ERROR [framework.browserify]:
/Users/user/Projects/example-d3-react/src/d3Chart.less:1
.d3 {
^
ParseError: Unexpected token
ERROR [karma]: [TypeError: Not a string or buffer]
This happens on all LESS files in the project. I have tried adding a LESS preprocessor to the karma.conf like so:
preprocessors: {
'src/*.less': ['less'],
'tests/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: [ 'reactify' ]
},
lessPreprocessor: {
options: {
paths: ['src'],
save: true,
rootpath: './'
},
additionalData: {
modifyVars: {
'bodyColor': 'grey',
'secondBoxColor': 'blue'
},
globalVars: {
'globalBoxColor': 'red'
}
},
transformPath: function(path) {
console.log("transforming");
return path.replace(/\.less$/, '.compiled.css');
}
},
Add the preprocessor explicitly to the config: plugins: ['karma-less-preprocessor']
None of the suggested answers helped me, but in case anyone is experiencing this problem, the solution that worked for me is just adding the project-specific less transform to the package.json file. E.g:
{
...
"browserify": {
"exclude": "*.spec.js",
"transform": [
"node-lessify",
"browserify-ng-html2js"
]
},
...
}
Build broke when doing this, since I was using the cmd line transform when building application through NPM. Removed the cmd line transform part since the package.json transform will apply the transform programmatically, and now it works again.