How to load babel-plugin-react-intl using babel-loader? - react-intl

I recently initialized a react app using create-react-app.
I ejected the app and I now have all the files exported to my main directory.
This set up creates a babel.dev.js instead of using .babelrc (it uses babel-loader).
I am trying to figure out how do I configure react-intl and babel-plugin-react-intl without the .babelrc file.
The documentation says .babelrc is recommended
Via .babelrc (Recommended)
.babelrc
{
"plugins": [
["react-intl", {
"messagesDir": "./build/messages/"
}]
]
}
What is the syntax to have this behavior with babel-loader? Right now the plugins in babel.dev.js look like this:
plugins: [
// class { handleClick = () => { } }
require.resolve('babel-plugin-transform-class-properties'),
// { ...todo, completed: true }
require.resolve('babel-plugin-transform-object-rest-spread'),
// function* () { yield 42; yield 43; }
[require.resolve('babel-plugin-transform-regenerator'), {
// Async functions are converted to generators by babel-preset-latest
async: false
}],
// Polyfills the runtime needed for async/await and generators
[require.resolve('babel-plugin-transform-runtime'), {
helpers: false,
polyfill: false,
regenerator: true,
// Resolve the Babel runtime relative to the config.
// You can safely remove this after ejecting:
moduleName: path.dirname(require.resolve('babel-runtime/package'))
}]
]
My components currently have the strings defined as follows:
const messages = defineMessages({
summaryTitle: {
"id": "checkout.section.title.summary",
"description": "Summary Section Title",
"defaultMessage": "Summary"
},
shippingTitle: {
"id": "checkout.section.title.shipping",
"description": "Shipping Section Title",
"defaultMessage": "Shipping"
}
});

Add the babel-plugin-react-intl to your plugins array like this:
plugins: [
..., // some plugins here
[require.resolve('babel-plugin-react-intl'), { messageDir: "./build/messages"}]
]
This will load the plugin passing the messageDir as an option to it.

Related

Jest-Vue-Quasar unit testing issue with ES modules

I'm have issues testing with Jest, I don't have much experience. My component is using my own ES Node Module, an it works fine in runtime, except when running the test., I'm using Vue3, Quasar and Jest.
I Tried different things such as mapping (moduleNameMapper) in the jest config file without success.
I get this error while running the test.
Cannot find module 'my-module' from 'src/Helpers.js'
In Helpers.js this is how is declared
import EventEmitter from 'events';
import { v4 as uuid } from 'uuid';
import { testMethod } from 'my-module';
This is my jest.config.js
const esModules = ['quasar/lang', 'lodash-es'].join('|');
/* eslint-env node */
module.exports = {
globals: {
__DEV__: true,
// TODO: Remove if resolved natively
// See https://github.com/vuejs/vue-jest/issues/175
'vue-jest': {
pug: { doctype: 'html' },
},
},
// noStackTrace: true,
// bail: true,
// cache: false,
verbose: true,
// watch: true,
collectCoverage: true,
reporters: [
'default',
[ 'jest-junit', {
outputDirectory: '<rootDir>/',
outputName: 'junit.xml',
} ]
],
coverageReporters: [
"json", "lcov", "text", "clover", "cobertura"
],
coverageDirectory: '<rootDir>/coverage',
collectCoverageFrom: [
'<rootDir>/src/**/*.vue',
//'<rootDir>/src/**/*.js',
'<rootDir>/src/**/*.ts',
//'<rootDir>/src/**/*.jsx',
//'<rootDir>/src/**/*.tsx',
],
coveragePathIgnorePatterns: ['/node_modules/', '.d.ts$'],
coverageThreshold: {
global: {
// branches: 50,
// functions: 40,
// lines: 50,
// statements: 50
},
},
testMatch: [
// Matches tests in any subfolder of 'src' or into 'test/jest/__tests__'
// Matches all files with extension 'js', 'jsx', 'ts' and 'tsx'
'<rootDir>/test/jest/__tests__/**/*.(spec|test).+(ts|js)?(x)',
'<rootDir>/src/**/*.jest.(spec|test).+(ts|js)?(x)',
],
// Extension-less imports of components are resolved to .ts files by TS,
// grating correct type-checking in test files.
// Being 'vue' the first moduleFileExtension option, the very same imports
// will be resolved to .vue files by Jest, if both .vue and .ts files are
// in the same folder.
// This guarantee a great dev experience both for testing and type-checking.
// See https://github.com/vuejs/vue-jest/issues/188#issuecomment-620750728
moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'ts', 'tsx'],
moduleNameMapper: {
'^~/(.*)$': '<rootDir>/$1',
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
'^layouts/(.*)$': '<rootDir>/src/layouts/$1',
'^pages/(.*)$': '<rootDir>/src/pages/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^boot/(.*)$': '<rootDir>/src/boot/$1',
'.*css$': '#quasar/quasar-app-extension-testing-unit-jest/stub.css',
},
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
transformIgnorePatterns: [`<rootDir>/node_modules/(?!(${esModules}))`],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
};
.babelrc
{
"plugins": ["#babel/plugin-syntax-dynamic-import"],
"env": {
"test": {
"plugins": ["dynamic-import-node"],
"presets": [
[
"#babel/preset-env",
{
"modules": "commonjs",
"targets": {
"node": "current"
}
}
]
]
}
}
}

Using Webpack's Coffee-Loader without explicitly stating ".coffee" file extension

preface
I am currently switching our build process over from Browserify to Webpack. As the project uses a great deal of coffee-script, I have many import statements such as:
require('./coffee-file-without-extension') # note the lack of .coffee
require('./legacy-js-file-without-extension') # note the lack of .js
problem
Browserify handles the absence of the file extension just fine. Webpack seems to have issue per this error:
Module not found: Error: Can't resolve './wptest-req' in '/Users/jusopi/Dev/Workspaces/nx/nx-ui/src'
I setup a super simple test project for this where I have the following files:
wptest.coffee
require('./wptest-req')
wptest-req.coffee
module.exports = {}
webpack.config.js
const path = require('path');
const webpack = require('webpack')
module.exports = {
entry: {
main: './src/wptest.coffee'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
})
],
module: {
rules: [
{
test: /\.coffee$/,
use: [
{
loader: 'coffee-loader',
options: { sourceMap: true }
}
]
}
]
}
};
end-goal
I am hoping I do not have to go over every file in our application and append .coffee to all require statements for coffee files if at all possible.
While this solution is not specific to coffee-loader, it did resolve my issue. I needed to add a resolve object to my configuration:
const path = require('path');
const webpack = require('webpack')
module.exports = {
entry: {
main: './src/main.coffee'
// other: './src/index2.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
})
],
module: {
rules: [
{
test: /\.coffee$/,
use: [
{
loader: 'coffee-loader',
options: { sourceMap: true }
}
]
}
]
},
resolve: {
extensions: [ '.coffee', '.js' ]
}
};
src - https://github.com/webpack-contrib/coffee-loader/issues/36

Browsersync doesn't detect file changes with Drupal Basic Theme Grunt config

When I use BrowserSync directly from the command line it works fine. But when I use the Grunt file from the Drupal Basic theme, BrowserSync is not detecting changes being made to the SASS and CSS files. Whereas the SASS to CSS conversion is working fine...
EDIT: when I use 'css/base/*.css' instead of 'css/{,*/}*.css' it works. So this must be a syntax issue. Any idea for the right syntax?
/**
* #file
*/
module.exports = function(grunt) {
// This is where we configure each task that we'd like to run.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
// This is where we set up all the tasks we'd like grunt to watch for changes.
scripts: {
files: ['js/source/{,*/}*.js'],
tasks: ['uglify'],
options: {
spawn: false,
},
},
images: {
files: ['images/source/{,*/}*.{png,jpg,gif}'],
tasks: ['imagemin'],
options: {
spawn: false,
}
},
vector: {
files: ['images/source/{,*/}*.svg'],
tasks: ['svgmin'],
options: {
spawn: false,
}
},
css: {
files: ['sass/{,*/}*.{scss,sass}'],
tasks: ['sass']
}
},
uglify: {
// This is for minifying all of our scripts.
options: {
sourceMap: true,
mangle: false
},
my_target: {
files: [{
expand: true,
cwd: 'js/source',
src: '{,*/}*.js',
dest: 'js/build'
}]
}
},
imagemin: {
// This will optimize all of our images for the web.
dynamic: {
files: [{
expand: true,
cwd: 'images/source/',
src: ['{,*/}*.{png,jpg,gif}' ],
dest: 'images/optimized/'
}]
}
},
svgmin: {
options: {
plugins: [{
removeViewBox: false
}, {
removeUselessStrokeAndFill: false
}]
},
dist: {
files: [{
expand: true,
cwd: 'images/source/',
src: ['{,*/}*.svg' ],
dest: 'images/optimized/'
}]
}
},
sass: {
// This will compile all of our sass files
// Additional configuration options can be found at https://github.com/sindresorhus/grunt-sass
options: {
sourceMap: true,
// This controls the compiled css and can be changed to nested, compact or compressed.
outputStyle: 'expanded',
precision: 5
},
dist: {
files: {
'css/base/base.css': 'sass/base/base.sass',
'css/components/components.css': 'sass/components/components.sass',
'css/components/tabs.css': 'sass/components/tabs.sass',
'css/components/messages.css': 'sass/components/messages.sass',
'css/layout/layout.css': 'sass/layout/layout.sass',
'css/theme/theme.css': 'sass/theme/theme.sass',
'css/theme/print.css': 'sass/theme/print.sass'
}
}
},
browserSync: {
dev: {
bsFiles: {
src : [
'css/{,*/}*.css',
'templates/{,*/}*.twig',
'images/optimized/{,*/}*.{png,jpg,gif,svg}',
'js/build/{,*/}*.js',
'*.theme'
]
},
options: {
watchTask: true,
// Change this to "true" if you'd like the css to be injected rather than a browser refresh. In order for this to work with Drupal you will need to install https://drupal.org/project/link_css keep in mind though that this should not be run on a production site.
injectChanges: true,
proxy: "dev.localhost"
}
}
},
});
// This is where we tell Grunt we plan to use this plug-in.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-svgmin');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
// Now that we've loaded the package.json and the node_modules we set the base path
// for the actual execution of the tasks
// grunt.file.setBase('/')
// This is where we tell Grunt what to do when we type "grunt" into the terminal.
// Note: if you'd like to run and of the tasks individually you can do so by typing 'grunt mytaskname' alternatively
// you can type 'grunt watch' to automatically track your files for changes.
grunt.registerTask('default', ['browserSync','watch']);
};
So, I found the solution. Apparently the official Grunt pattern should be like this:
'css/**/*.css'

Configure Polymer web-component-tester to use a Selenium Grid server

I need to configure the Polymer web-component-tester to use a Selenium Grid running at http://jenkins.myapp.corp.web:4444/wd/hub so I can run my tests on Jenkins. What is the Grunt config for this? I guessing something like this:
'wct-test': {
local: {
options: {
activeBrowsers: [{
browserName: 'chrome',
url: 'http://jenkins.myapp.corp.web:4444/wd/hub'
}]
}
}
}
It turns out there was a bug with web-component-tester that has been fixed in the latest release. We ended up getting it working with our grid using this config:
var os = require('os');
...
'wct-test': {
local: {
options: {
remote: false,
activeBrowsers: [{
browserName: "chrome",
url: "http://jenkins.myapp.corp.web:4444/wd/hub"
}],
webserver: {
hostname: os.hostname()
}
}
}
}
It seems that you can modify your wct.conf.js and set your grid configuration:
module.exports = {
// See https://github.com/Polymer/web-component-tester/blob/master/runner/config.js#L47-54
activeBrowsers: [
{
// Accepts anything wd does: https://github.com/admc/wd#browser-initialization
url: 'http://user:apiKey#your.selenium.server/wd/hub',
// ... any other capabilities you like:
browserName: 'theBrowser',
}
],
plugins: {
local: false,
sauce: false,
}
};
The correct configuration for wct.conf.json should be as follows. You should change url of the sample to your selenium grid url.
{
"....":"....",
"activeBrowsers": [{
"browserName": "chrome",
"url": "http://selenium-hub-selenium.apps.com.tr/wd/hub"
}],
"plugins": {
"local": {
"disabled": true
},
"sauce":{
"disabled": true
}
}
}

Dojo Build System - custom paths hash not working

I am trying to switch from the old dojo build system to the new one. I have been pulling my hair out but I can't seem to get the build script to pick up the custom paths mapping that i specified in the building profile. So if my project structure is like:
/www/dojo
/www/dojox
/www/dijit
/www/app.profile.js
/www/myapp/package.json #links to myapp.profile.js
/www/myapp/myapp.profile.js #standard package profile stub
#with test,copyOnly,amd
/www/myapp/main.js
/www/myapp/bar/hello.js
/www/myapp/bar/sometext.html
The files look like below:
//-------------------------------------------
//FILE: app.profile.js
//-------------------------------------------
var profile = (function(){
return {
basePath: ".",
releaseDir: "builds",
releaseName: "v0_0_1",
optimize: "closure",
cssOptimize: "comments",
action: "release",
packages:[
{
name: "dojo",
location: "dojo/dojo"
},
{
name: "myapp",
location: "myapp"
}
],
prefixes: {
"foo": "bar" //doesn't seem to work?
},
paths: {
"foo": "bar" //doesn't seem to work?
},
loaderConfig:{
paths: {
"foo": "bar" //doesn't seem to work?
},
},
layers: {
"mypp/myapp-release": {
include: [
"myapp/main"
]
}
}
};
})();
//--------------------------------------
//FILE: main.js
//--------------------------------------
require(["dojo/_base/html", "foo/hello", "dojo/text!foo/sometext.html"],
function(html, Bar, sometext){
alert(sometext);
}
);
//--------------------------------------
//FILE: hello.js
//--------------------------------------
require([ ],
function(){
alert("hello!");
}
);
And I am running the build command with:
node /www/dojo/dojo.js load=build /www/app.profile.js
The build script would tell me that the dependency "foo/hello" is not found, even though it should have been mapped to bar/hello.js ; the same goes for foo/sometext.html .
Any help would be really appreciated; I don't want to keep pulling my hair til I'm bald! :D