[UPDATE]
The original title of this post was : "Bad karma, lost data" and standed for the mind word play, much more for the rimes than for a real fact. So I decided to alter it, for the sake of correctness and courtesy.
[UPDATE]
Hi there, I've a very classical program directory strcture:
dist/
karam.conf.js
node_modules/
package.json
rollup.config.js
src/
fp/
list.js # imports maybe.js
matbe.js
test/
fp/
list.specs.js
maybe.specs.js
I'm trying to preprocess the tests with rollup. My karma.conf.js is just like :
# karma.conf.js
const buble = require('#rollup/plugin-buble')
const resolve = require('#rollup/plugin-node-resolve').default
// console.log({ resolve })
module.exports = function(config) {
config.set({
basePath : '',
files: [
{
pattern: 'src/fp/*.js', watched: true
},{
pattern: 'test/fp/*.specs.js', watched: true
}
],
watch: true,
preprocessors: {
'src/fp/*.js': ['rollup2'],
'test/fp/*.specs.js': ['rollup2']
},
rollup2Preprocessor: {
output: {
name: 'fptest',
format: 'iife'
},
plugins: [
buble(),
resolve()
]
}
});
}
When I start karma, with npm or from CLI with "karma start --log-level debug", I get 4 empty bundles and get the error message "Error during file loading or preprocessing
TypeError: output is not iterable".
So I could not test my program properly.
What's happening and how to fix that ?
Thanks for replies, Regards.
Looking at your module loader, I suggest using a karma plugin like karma-rollup-preprocessor to bundle your module before running tests. This will bundle and wire-up your modules properly for testing.
And you don't need to specify all your files under files array.
files: [
'test/**/*.js'
],
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 the current folder structure (where test is in the root of my directory):
test
unit
helper
helper.js
helper2
helper2.js
My jest.config.js looks like the following (this config file is in the root of my folder):
module.exports = {
testEnvironment: 'node',
collectCoverage: true,
collectCoverageFrom: ['**/*.{js,jsx}', '!**/node_modules/**'],
coverageDirectory: './coverage',
roots: ['<rootDir>/test'],
coverageReporters: ['text'],
rootDir: '.',
reporters: ['default'],
};
When I run the command: jest --verbose I am getting the error that No tests found, existing with code 1. Is there something wrong in my jest config that I need to modify?
Even that you've modified the roots jest still has testMatch. By default it's value is
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[tj]s?(x)"
],
so you can change it to:
"testMatch": [
"**/*.[jt]s?(x)",
],
Note: by running jest --showConfig you'll get a nice overview of all of the configurations and an idea of what else might need to be changed
Some weeks ago I updated all my dependencies using npm ... --force and whatnot. Some may say this wasn't the greatest choice, but still...
I don't know exactly why, but since I updated my NPM dependencies, webpack doesn't generate my output bundle anymore, which it did before just fine.
The project is laid out as following
- app/
|- dist/
|- app-server/ (Node + Express)
|- app.js
|- ...
|- app-frontend/ (Vue + Bootstrap)
|- dist/ (HTML/CSS/etc)
webpack.config.js (Run from inside app-server/):
const nodeExternals = require('webpack-node-externals');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = [
{
name: 'server',
entry: './app.js',
output: {
path: __dirname + '/../dist',
filename: 'app_bundle.js',
},
mode: 'production',
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [
nodeExternals({})
],
plugins: [
new CopyPlugin({
patterns: [{ from: '../app-frontend/dist', to: '../dist/frontend' }],
})
],
stats: {
colors: true,
hash: false,
version: false,
timings: false,
assets: false,
chunks: false,
modules: false,
reasons: false,
children: false,
source: false,
errors: false,
errorDetails: false,
warnings: false,
publicPath: false,
},
},
];
The logs only say:
Entrypoints:
app (434 KiB)
css/chunk-vendors.f6f30965.css
js/chunk-vendors.98eb6b3c.js
css/app.a6ef7e2c.css
js/app.4fd07954.js
Child server:
Built at: 06.10.2020 19:07:17
Entrypoint main = app_bundle.js
and no file gets generated. I tried chmod 775 dist/ to no avail. I re-cloned the repo, to no avail. I deleted the CopyPlugin part, to no avail.
Hey, I even got to the root directory of my Ubuntu and did find * | app_bundle.js -r and it didn't find anything besides logs that have this name in it, which upon opening, are the log presented above.
I'm scratching my head on this since yesterday.
Any help is greatly appreciated!
I eventually figured it out!
The problem was that I was shooting myself in the foot by adding these lines:
stats: {
errors: false,
errorDetails: false,
warnings: false,
}
Which basically meant that it just exited with error code 1, but without telling me the error.
I thought that these parameters were to disable the errors within the browser. Apparently I was wrong.
Once I set those above to true and running webpack again, I saw that it indeed had some errors.
In my case, the error was that I was creating files (under Windows) with the name (for example) orderController.js, but require them calling ../../OrderController, which is, as you may see, not exactly equal. My file has a o and the script contains a capital O, which under Windows worked just fine, but I forgot that Linux (the server the production runs on) is case-sensitive.
After fixing those errors, webpack ran just fine and generated my bundle at the specified output directory!
I have a file in my project called test.js
I don't import/require it anywhere which means my webpack won't call babel-loader for that js file.
Question: what I want is to move test.js into /dist folder, but as a compiled/transpiled. What's the best practice for it?
What I tried: I tried to use a copy-webpack-plugin and use its transform parameters before copying the file, but I can't seem to find the good babel package.
{
from: 'test.js',
to: '/dist/test.js',
transform(content, path) {
//what do I write here?
},
}
The simplest approach I could think about is to use several entry points like this:
{
entry: {
a: "./your-main-stuff",
b: "./your-single-file",
},
output: {
path: path.join(__dirname, "dist"),
filename: "[name].js"
}
}
which will create your a.js main bundle and b.js file in __dirname/dist folder both transpiled provided you used corresponding loader(s).
And from copy-webpack-plugin docs section:
webpack-copy-plugin is not designed to copy files generated from the
build process; rather, it is to copy files that already exist in the
source tree, as part of the build process.
so it seems to be difficult (if possible) making it move transpiled files.
Update. If you want to output files into different folders w/o changing your src folder, additonal tools needed. For your case (just 1 file) I would write a simple script and add it into package.json script section combined with webpack call like:
"scripts": {
"dev": "webpack && babel path-to-script.js --out-file path-to-script-compiled.js"
}
Just like in the previous answer, initially I went with the "scripts" entry in package.json that runs babel. But for a number of reasons I wanted to use webpack 5 to do the job. So after failing with webpack-copy-plugin and a good amount of digging around I came to this solution:
let config = {
entry: [
glob.sync(srcDir + '/**/*.js') // get all .js files from the source dir
],
output : {
filename : '[name].rem.js', // webpack wants to bundle - it can bundle here ;)
path: outDir
},
resolve: {
alias: {
'app': appDir
}
},
plugins: [
new RemoveEmptyScriptsPlugin({extensions: ['js'], scriptExtensions: /\.rem\.js/}) // for all .js source files that get bundled remove the bundle .rem.js file
],
module: {
rules:[{
test: /\.jsx?$/,
type: 'asset/resource', // get webpack to take it out instead of bundling
generator: {
filename: ({filename}) => filename // return full file name so directory structure is preserved
},
use: {
loader: 'babel-loader',
options: {
targets: { node: 16 },
presets: [
['#babel/preset-env', { modules: 'commonjs' /* transpile import/export */}],
]
}
}
}]
}
};
// Since the code does not go through the full pipeline and imports are not getting resolved, aliases will remain in the code.
// To resolve them it takes to hack the aliases object into the babel config
config.module.rules[0].use.options.plugins.push(['babel-plugin-webpack-alias-7', {config: {resolve: {alias: config.resolve.alias}}}];
And it does a good job but beware that it takes to use the patched versions of the two plugins (unless the patches have been merged already)!
I have a Typescript project:
myproject
|
+-src (folder)
| |
| +-main.ts
| +-stringHandler.ts
| +-disposable.ts
+-out (folder)
| |
| +-...
+-Gruntfile.js
In my Grunt configuration I have a 2-step task which compiles all .ts files in myproject/src/ and generates corresponding .js files into myproject/out/. So after the first step of the task is complete, I have the following:
myproject
|
+-out (folder)
|
+-main.js
+-stringHandler.js
+-disposable.js
Bundling
The second step of the task is generating bundle file myproject.js. I am using RequireJS for this purpose.
I have installed grunt-contrib-requirejs. The Gruntfile.js file handling the bundling task is as follows (showing only relevant parts in the file):
module.exports = function(grunt) {
var config = {
pkg: grunt.file.readJSON('package.json'),
requirejs: {
compile: {
options: {
baseUrl: "out",
bundles: {
'myproject': ['main', 'stringHandler', 'disposable']
},
out: 'out/myproject.js'
}
}
}
};
grunt.initConfig(config);
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['compile', 'requirejs']);
};
When Grunt reaches requirejs, after successfully compiling the project, I get the following error:
Running "requirejs:compile" (requirejs) task { [Error: Error: Missing
either a "name", "include" or "modules" option
at Function.build.createConfig (C:\Users\myuser\Documents\myproject\node_modules\grunt-contrib-requirejs\node_modules\requirejs\bin\r.js:29567:19)
] originalError: [Error: Missing either a "name", "include" or
"modules" option] }
I can understand there are missing parameters, but when I use name I get other errors. I guess there must be something wrong at a more generic level. What is the correct configuration format? Thanks
This assumes main.ts is your application's entry point and that it contains a require.config section with your application dependencies (libraries and shims).
First, move the require.config section out of main.ts and into its own file, config.ts. Leave the application bootstrap code in main.ts.
Then determine where you want this optimized application code deployed. Let's assume it is to a directory named build, which is parallel to your src and out folders.
Update you Gruntfile to reflect this configuration:
requirejs: {
compile: {
options: {
baseUrl: "out",
mainConfigFile: "out/config.js",
modules: [
{ name: "main" }
],
dir: "build",
optimize: "none" // skip compression while debugging
}
}
}
You can read more about each of these config options at http://requirejs.org/ but here's the basic rundown:
baseUrl: Where the source JS code lives.
mainConfigFile: Points to the config object mentioned above. It tells the plugin where the dependencies live. This obviates the need to specify and manually update the list of dependencies in two places.
modules: Is an array of application bootstraps. In this case a list of one, main.js.
dir: Where the optimized application will be generated. Note that your dependencies will also be copied here.
optimize: I left this off so you can easily debug the resulting app under ./build. Remove it when you're happy and the plugin will optimize (compress and munge) your build files.