I have the following structure
components/
index.js
Messages/
index.js
error.jsx
info.jsx
success.jsx
Messages/index.js export the three messages as :
export {Info} from './info'
export {Error} from './error'
export {Success} from './success'
And components/index.js does the following:
import * as Message from './Message'
export {Message}
Is there a way for me to do it without the import?
I am using webpack and Babel with es2015 presets
According to Mozilla's ES2015 documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export you can just do
export * from './Messages';
Related
I can't make my code work when running the project normally and running in Jest.
Running the project requires this kind of imports for dayjs:
import * as dayjs from 'dayjs';
import * as utc from 'dayjs/plugin/utc';
import * as customParseFormat from 'dayjs/plugin/customParseFormat';
npm run dev (nodemon --exec ./node_modules/.bin/ts-node ./src/app.ts): No issues
Jest: TypeError: t is not a function
Running the Jest tests requires this kind of imports for dayjs:
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import customParseFormat from 'dayjs/plugin/customParseFormat';
npm run dev (nodemon --exec ./node_modules/.bin/ts-node ./src/app.ts):
dayjs.extend(utc);
^
TypeError: Cannot read property 'extend' of undefined`
Jest: Success!
So now it is impossible for me to write Tests. Why is it transpiled differntly?
In my case,
tsconfig.json
{
"compilerOptions": {
"esModuleInterop": true
}
}
solved it.
I switched to ts-jest and it solved my problem. I was assuming that I could write JS tests to test the TS code but I suppose that is not possible.
I am trying to get the mongodb collection name from an environment variable defined in .env. It looks like the model is initialised before the .env is read.
#model({
name: 'MyType',
settings: {
mongodb: process.env.COLLECTION_NAME,
},
})
The process.env.COLLECTION_NAME is, at this point, undefined
Any way to externalised the collection name?
Many thanks for the help.
By default, Node.js does not read from .env.
To read from .env, we need to utilize the dotenv package.
Since models are resolved through the Booter during startup, hence we need to call dotenv.config() before app.boot().
Update index.ts as follows:
// At the top of the file
import dotenv from 'dotenv';
...
// Inside the main function
// dotenv.config() must appear before app.boot()
dotenv.config()
...
app.boot();
app.start();
This would cause dotenv to overwrite process.env with the values in .env where necessary.
Further reading:
https://www.npmjs.com/package/dotenv
How do I setup the dotenv file in Node.js?
in your
src/index.ts
import {ApplicationConfig, MyApplication} from './application';
require('dotenv').config();
export * from './application';
and your .env file in the "root" of your project
I am just getting started with the Jest test framework and while straight up unit tests work fine, I am having massive issues testing any component that in its module (ES module via babel+webpack) requires a HTML file.
Here is an example:
import './errorHandler.scss';
import template from './errorHandler.tmpl';
class ErrorHandler {
...
I am loading the component specific SCSS file which I have set in Jest's package.json config to return an empty object but when Jest tries to run the import template from './errorHandler.tmpl'; line it breaks saying:
/Users/jannis/Sites/my-app/src/scripts/errorHandler/errorHandler.tmpl.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<div class="overlay--top">
^
SyntaxError: Unexpected token <
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)
My Jest config from package.json is as follows:
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/test/setupFile.js",
"moduleDirectories": ["node_modules"],
"moduleFileExtensions": ["js", "json", "html", "scss"],
"moduleNameMapper": {
"^.+\\.scss$": "<rootDir>/test/styleMock.js"
}
}
It seems that the webpack html-loader is not working correctly with Jest but I can't find any solution on how to fix this.
Does anyone know how I can make these html-loader imports work in my tests? They load my lodash template markup and i'd rather not have these at times massive HTML chunks in my .js file so i can omit the import template from x part.
PS: This is not a react project, just plain webpack, babel, es6.
I encountered this specific problem recently and creating your own transform preprocesser will solve it. This was my set up:
package.json
"jest": {
"moduleFileExtensions": [
"js",
"html"
],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
}
}
NOTE: babel-jest is normally included by default, but if you specify a custom transform preprocessor, you seem to have to include it manually.
test/utils/htmlLoader.js:
const htmlLoader = require('html-loader');
module.exports = {
process(src, filename, config, options) {
return htmlLoader(src);
}
}
A bit late to the party, but wanted to add that there is also this html-loader-jest npm package out there to do this if you wanted to go that route.
Once you npm install it you will add it to your jest configuration with
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.html?$": "html-loader-jest"
}
For Jest > 28.x.x with html-loader:
Create a custom transformer as documented here.
jest/html-loader.js
const htmlLoader = require("html-loader");
module.exports = {
process(sourceText) {
return {
code: `module.exports = ${htmlLoader(sourceText)};`,
};
},
};
Add it to your jest config.
jest.config.js
...
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.html$": "<rootDir>/jest/html-loader.js",
},
...
It will fix the error : Invalid return value: process() or/and processAsync() method of code transformer found at "<PATH>" should return an object or a Promise resolving to an object.
Maybe your own preprocessor file will be the solution:
ScriptPreprocessor
Custom-preprocessors
scriptpreprocessor: The path to a module that provides a synchronous function from pre-processing source files. For example, if you wanted to be able to use a new language feature in your modules or tests that isn't yet supported by node (like, for example, ES6 classes), you might plug in one of many transpilers that compile ES6 to ES5 here.
I created my own preprocessor when I had a problems with my tests after added transform-decorators-legacy to my webpack module loaders.
html-loader-jest doesn't work for me. My workaround for this:
"transform": {
'\\.(html)$': '<rootDir>/htmlTemplateMock.html'
}
htmlTemplateMock.html is empty file
For Jest 28+ you can use jest-html-loader to make Jest work with code that requires HTML files.
npm install --save-dev jest-html-loader
In your jest config, add it as a transformer for .HTML files:
"transform": {
"^.+\\.html?$": "jest-html-loader"
},
In my ember-cli app i have installed an addon called 'ember-cli-selectize'. Looking at the directory structure i can see that its files are located at /node_modules/ember-cli-selectize'. Now i want to create a custom component that extends this addon. How do i import/require it? I've tried these and none seems to work:
var EmberSelectize = require('/ember-cli-selectize/app/components/ember-selectize');
import EmberSelectize from 'components/ember-selectize';
import EmberSelectize from 'node_modules/ember-cli-selectize/addon/components/ember-selectize';
import EmberSelectize from 'ember-cli-selectize/addon/components/ember-selectize';
i always get this 'Could not find module' error no matter what. I need to somehow import/require it to do something like
import EmberSelectize from 'wherever/it/is';
export default EmberSelectize.extend({
//my own customizations
})
You were close with:
import EmberSelectize from 'components/ember-selectize';
Addons namespace themselves - in this case, ember-cli-selectize. So, just add the namespace to your import:
import EmberSelectizeComponent from 'ember-cli-selectize/components/ember-selectize';
then you can extend:
export default EmberSelectizeComponent.extend({ });
After setting up the folder structure for my Gulp project, I was wondering how to do paths in browserify, and found this page: https://github.com/substack/browserify-handbook#organizing-modules. It recommends putting common application parts in a subfolder of node_modules. This appears to be working, it's getting the files, but it's not applying my coffeeify transform, so it's throwing errors because it's trying to interpret them as JS. Any ideas how to fix this? This is my browserify config:
browserify: {
// Enable source maps
debug: true,
// Additional file extentions to make optional
extensions: ['.coffee', '.hbs'],
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [{
entries: src + '/javascript/app.coffee',
dest: dest,
outputName: 'app.js'
}, {
entries: src + '/javascript/head.coffee',
dest: dest,
outputName: 'head.js'
}]
}
and these are the relevant bits form my package.json.
"browserify": {
"transform": [
"coffeeify",
"hbsfy"
]
}
Transfroms aren't applied to files in node_modules unless they are marked as being global: https://github.com/substack/node-browserify#btransformtr-opts. If you choose to make it global, be warned, the documentation suggests against it:
Use global transforms cautiously and sparingly, since most of the time
an ordinary transform will suffice.
You won't be able to specify the tranform in package.json:
You can also not configure global transforms in a package.json like
you can with ordinary transforms.
The two options are programmatically, by passing {global: true} as options or at the command line with the -g option:
browserify -g coffeeify main.coffee > bundle.js