Rollup Font Awesome CSS? - font-awesome

I'm including Font Awesome in a library project with:
import '#fortawesome/fontawesome-pro/css/all.min.css';
When running locally, this works fine and I can use the Font Awesome classes to create icons.
But after I rollup the project and include I get the error:
Module not found: Can't resolve '#fortawesome/fontawesome-pro/css/all.min.css'
Other CSS files are being bundled into an output css file. Why not that one? Here's my rollup.config.js.
import babel from 'rollup-plugin-babel';
import css from 'rollup-plugin-css-only';
export default {
input: 'src/index.js',
output: {
file: 'bundle.js',
format: 'cjs'
},
external: [
'react',
'react-dom',
'lodash',
'moment',
'react-router-dom',
],
plugins: [
babel({
exclude: "node_modules/**",
presets: ["#babel/preset-react", "#babel/preset-env"],
}),
css({
output: 'bundle.css'
})
],
};

This is likely caused by Rollup not being able to resolve the bare module specifier ('#fortawesome/fontawesome-pro...' instead of ./path/to/#fortawesome...').
Try adding the #rollup/plugin-node-resolve plugin:
import resolve from '#rollup/plugin-node-resolve';
export default {
//...
plugins: [
babel({
exclude: "node_modules/**",
presets: ["#babel/preset-react", "#babel/preset-env"],
}),
resolve(),
css({
output: 'bundle.css'
})
],
};
``

Related

vite does not build tailwind css

I installed tailwind and other tools using npm install -D tailwindcss postcss autoprefixer vite
I created tailwind and postcss config files using npx tailwindcss init -p
tailwind.config.js contains:
module.exports = {
content: [],
theme: {
extend: {},
},
plugins: [],
}
postcss.config.js contains:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
My CSS file exits in css\tailwind.css and contains:
#tailwind base;
#tailwind components;
#tailwind utilities;
The CSS file is linked to my HTMl page using <link href="/css/tailwind.css" rel="stylesheet" >
When I run vite, my app starts without build errors but tailwind output is not generated.
You need to adjust a few settings, feels like you're pretty close.
Edit Tailwind.config.js
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Start Vite building script with 'npm run dev' command.
// Open terminal
npm run dev
(Optional) Copy demo h1 property into your index file and test
<h1 class="text-3xl text-blue-700">Testing</h1>
This works for me. Once you've done what Tailwindcss says in its docs, in your vite.config.js (I tried this on JavaScript file. I am not sure if this works on TypeScript in the same way) import tailwindcss:
import tailwindcss from 'tailwindcss'
Then add tailwindcss as a PostCSS plugin like this:
css: {
postcss: {
plugins: [tailwindcss],
},
}
Once you've done that your vite.config.js will look like this:
/*Other imports*/
import tailwindcss from 'tailwindcss'
export default defineConfig({
plugins: [],
resolve: {
/*something*/
},
css: {
postcss: {
plugins: [tailwindcss],
},
},
});

#rollup/plugin-json with typescript not working

I have a valid appsettings.json file (according to jsonlint.com), I've set the tsconfig resolveJsonModule option to true. I'm importing #rollup/plugin-json and I've tried calling it at every position in the plugins chain. But I always get:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
So the plugin is firing (I think), but it can't parse the file, which seems to be valid. Rollup config looks like this:
import typescript from '#rollup/plugin-typescript';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from "#rollup/plugin-commonjs";
import dev from 'rollup-plugin-dev';
import copy from 'rollup-plugin-copy';
import replace from '#rollup/plugin-replace';
// Loaders for non-ts/js file types
import postcss from 'rollup-plugin-postcss';
import image from '#rollup/plugin-image';
import json from '#rollup/plugin-json';
console.log(`Node env is ${process.env.NODE_ENV}`);
// console.debug(process);
let isDevEnv = process.env.NODE_ENV === 'development';
let useMsw = process.env.USE_MSW;
const extensions = ['.cjs', '.js', '.jsx', '.json', '.ts', '.tsx', '.css', '.png'];
// const intro = useMsw
// ? 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = true'
// : 'global = window; window.NODE_ENV = process.env.NODE_ENV; window.USE_MSW = false';
const intro = `global = window; window.NODE_ENV = process.env.NODE_ENV; ${useMsw ? 'window.USE_MSW = true;' : ''}`;
export default {
input: [
'src/index.tsx'
],
output: {
intro: intro,
file: './dist/bundle.js',
format: 'es',
sourcemap: isDevEnv,
inlineDynamicImports: true,
},
plugins: [
postcss({}),
resolve({
extensions: extensions,
browser: true
}),
commonjs(),
typescript(),
replace({
'process.env.NODE_ENV': JSON.stringify('development')
}),
image(),
copy({
targets: [
{src: './src/index.html', dest: './dist/'},
{src: './src/mockServiceWorker.js', dest: './dist/'}
],
verbose: true
}),
isDevEnv && dev('dist', {
host: 'localhost'
}),
json(),
]
};
tsconfig looks like this:
{
"compilerOptions": {
"declaration": false,
"module": "ESNext",
"noImplicitAny": true,
"target": "ES2015",
"jsx": "react",
"allowSyntheticDefaultImports": true,
"allowJs": true,
"moduleResolution": "Node",
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": [
"src/**/*.tsx",
"src/**/*.ts",
"declaration.d.ts",
"src/components/TabularVIew/GridContainer/hooks"
],
"exclude": ["node_modules"]
}
and the actual json file looks like this:
{
"HUB_URL": "theHubUrl",
"AUTH_ENDPOINT": "https://localhost:44330/API/Dispatch/Authentication/v1.0/authenticate",
"POSITION_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/position",
"SUMMARY_ENDPOINT": "https://localhost:44330/API/Dispatch/Data/v1.0/summaries",
"GLOBAL_TLM": 1,
"PERIOD_LENGTH_MINUTES": 30,
"EFA_BLOCKS": [
[23,0,1,2],
[3,4,5,6],
[7,8,9,10],
[11,12,13,14],
[15,16,17,18],
[19,20,21,22]
]
}
and the rollup output is this:
(!) Plugin json: Could not parse JSON file
appsettings.json
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
appsettings.json (2:10)
Pretty frustrating because on one line it says 'plugin json can't parse', then the next log line tells me I need plugin json???. Invalid file, file not found, plugin not installed, these I could understand. Possibly a clash between tsc and the plugin. Out of ideas..
Suggestions welcome.
Thanks.
The reason for that can be the json file encoding is utf8withbom. Try to encode the file as utf8.
Not really an answer, but the behaviour appears to be linked to some aggressive caching. Either by npm or typescript. I opened up the project in vscode, hosed node_modules, ran npm install, usual drill.. created a new JSON file, installed the rollup json plugin, and it built. Sum total of learning: 0;

Webpack runs Babel against PNG

Here is my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
javascript: './static/jsx/main.jsx'
},
output: {
path: path.resolve('./static/js/app/'),
filename: 'bundle.js'
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'source-map'
}
],
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader?limit=25000',
include: path.resolve('./static/images/')
}
]
},
};
Here is example of using png in a jsx file
import L from 'leaflet';
import { LayersControl, Marker, Popup } from 'react-leaflet';
const src = require('./marker-icon-red.png');
//Extend the Default marker class
let RedIcon = L.Icon.Default.extend({
options: {
iconUrl: src
}
});
let redIcon = new RedIcon();
When I run webpack for my jsx files (using gulp)
gulp.task('transform', function() {
return gulp.src(path.JS)
.pipe(webpack( require('./webpack.config.js') ))
.on('error', swallowError)
.pipe(gulp.dest(path.DEST_BUILD));
});
I get this error
[15:14:10] Starting 'transform'...
Error in plugin 'webpack-stream'
Message:
./static/jsx/map/markers/marker-icon-red.png
Module parse failed: D:\work\Cycling\static\jsx\map\markers\marker-icon-red.png
Unexpected character '?' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '?' (1:0)
at Parser.pp$4.raise (D:\work\Cycling\node_modules\webpack\node_modules\acor
n\dist\acorn.js:2221:15)
at Parser.pp$7.getTokenFromCode (D:\work\Cycling\node_modules\webpack\node_m
odules\acorn\dist\acorn.js:2756:10)
at Parser.pp$7.readToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2477:17)
at Parser.pp$7.nextToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2468:15)
at Parser.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:515:10)
at Object.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:3098:39)
at Parser.parse (D:\work\Cycling\node_modules\webpack\lib\Parser.js:902:15)
at DependenciesBlock.<anonymous> (D:\work\Cycling\node_modules\webpack\lib\N
ormalModule.js:104:16)
at DependenciesBlock.onModuleBuild (D:\work\Cycling\node_modules\webpack-cor
e\lib\NormalModuleMixin.js:310:10)
at nextLoader (D:\work\Cycling\node_modules\webpack-core\lib\NormalModuleMix
in.js:275:25)
# ./static/jsx/map/markers/parkings_markers.jsx 19:10-42
[15:14:21] Version: webpack 1.13.2
Asset Size Chunks Chunk Names
bundle.js 1.48 MB 0 [emitted] javascript
ERROR in ./static/jsx/map/markers/marker-icon-red.png
Module parse failed: D:\work\Cycling\static\jsx\map\markers\marker-icon-red.png
Unexpected character '?' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '?' (1:0)
at Parser.pp$4.raise (D:\work\Cycling\node_modules\webpack\node_modules\acor
n\dist\acorn.js:2221:15)
at Parser.pp$7.getTokenFromCode (D:\work\Cycling\node_modules\webpack\node_m
odules\acorn\dist\acorn.js:2756:10)
at Parser.pp$7.readToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2477:17)
at Parser.pp$7.nextToken (D:\work\Cycling\node_modules\webpack\node_modules\
acorn\dist\acorn.js:2468:15)
at Parser.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:515:10)
at Object.parse (D:\work\Cycling\node_modules\webpack\node_modules\acorn\dis
t\acorn.js:3098:39)
at Parser.parse (D:\work\Cycling\node_modules\webpack\lib\Parser.js:902:15)
at DependenciesBlock.<anonymous> (D:\work\Cycling\node_modules\webpack\lib\N
ormalModule.js:104:16)
at DependenciesBlock.onModuleBuild (D:\work\Cycling\node_modules\webpack-cor
e\lib\NormalModuleMixin.js:310:10)
at nextLoader (D:\work\Cycling\node_modules\webpack-core\lib\NormalModuleMix
in.js:275:25)
# ./static/jsx/map/markers/parkings_markers.jsx 19:10-42
[15:14:21] Finished 'transform' after 11 s
As I understood it's babel tries to read png file, although I told webpack that png files should be treated by url-loader not babel.
What am I doing wrong?
Thanks for help!
Your url-loader config is set to only consider images from ./static/images, because of the include property:
{
test : /\.(jpg|png)$/,
loader : 'url-loader?limit=25000',
include : path.resolve('./static/images/')
}
However, the image you're trying to require is located in a different directory (./static/jsx/map/markers/).
If you remove the include, it'll probably work.
Renaming img1.PNG to img1.png solved it in my case.

Does Jest support ES6 import/export?

If I use import/export from ES6 then all my Jest tests fail with error:
Unexpected reserved word
I convert my object under test to use old school IIFE syntax and suddenly my tests pass. Or, take an even simpler test case:
var Validation = require('../src/components/validation/validation'); // PASS
//import * as Validation from '../src/components/validation/validation' // FAIL
Same error. Obviously there's a problem with import/export here. It's not practical for me to rewrite my code using ES5 syntax just to make my test framework happy.
I have babel-jest. I tried various suggestions from GitHub issues. It is no go so far.
File package.json
"scripts": {
"start": "webpack-dev-server",
"test": "jest"
},
"jest": {
"testPathDirs": [
"__tests__"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testFileExtensions": ["es6", "js"],
"moduleFileExtensions": ["js", "json", "es6"]
},
File babelrc
{
"presets": ["es2015", "react"],
"plugins": ["transform-decorators-legacy"]
}
Is there a fix for this?
From my answer to another question, this can be simpler:
The only requirement is to configure your test environment to Babel, and add the ECMAScript 6 transform plugin:
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
And that's it. Jest will enable compilation from ECMAScript modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.
UPDATE 2020 - native support of ECMAScript modules (ESM)
According to this issue, there is native support of ESM from jest#25.4.0. So you won't have to use babel anymore. At the time of writing this answer (05/2020), to activate that you need to do three simple things:
Make sure you don't transform away import statements by setting transform: {} in config file
Run node#^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
Run your test with jest-environment-node or jest-environment-jsdom-sixteen.
So your Jest configuration file should contain at least this:
export default {
testEnvironment: 'jest-environment-node',
transform: {}
...
};
And to set --experimental-vm-modules flag, you will have to run Jest as follows:
node --experimental-vm-modules node_modules/jest/bin/jest.js
Also note in the Github issue that this approach does not yet support the jest object. So you may need to import it manually:
import {jest} from '#jest/globals'
(I hope this will change in the future)
For an updated configuration, I'm using https://babeljs.io/setup#installation
Select JEST and be happy:
As a reference, the current configuration:
npm install --save-dev babel-jest
In your package.json file, make the following changes:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
Install babel preset:
npm install #babel/preset-env --save-dev
Create a .babelrc file:
{
"presets": ["#babel/preset-env"]
}
Run your tests:
npm run test
In package.json, kindly set like this one: "test": "node --experimental-vm-modules node_modules/.bin/jest"
Should be good!
It's a matter of adding stage-0 to your .babelrc file. Here is an example:
{
"presets": ["es2015", "react", "stage-0"],
"plugins": ["transform-decorators-legacy"]
}
I encountered the same issue.
These are what I did:
yarn add --dev babel-jest #babel/core #babel/preset-env
Make file jest.config.js in rootDir.
module.exports = {
moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "json"],
transform: {
'^.+\\.(js|jsx)?$': 'babel-jest'
},
testEnvironment: 'node',
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1'
},
testMatch: [
'<rootDir>/**/*.test.(js|jsx|ts|tsx)', '<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};
Then make file babal.config.js in rootDir.
Go like this:
module.exports = {
"presets": ["#babel/preset-env"]
}
Below is how I setup jest, typescript and ES Modules for my project.
jest.config.js
/**
* #type {import('ts-jest/dist/types').InitialOptionsTsJest}
* To configure ESM support, see: https://kulshekhar.github.io/ts-jest/docs/guides/esm-support
*
**/
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
useESM: true
}
},
setupFiles: ['<rootDir>/__tests__/setup.ts'],
};
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"outDir": "./dist",
"moduleResolution": "node",
// "strict": true,
"esModuleInterop": true,
"inlineSourceMap": true,
}
}
package.json scripts and devDependencies
"scripts": {
"start": "node ./dist/server.js",
"dev": "tsc-watch --onSuccess \"node ./dist/server.js\"",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
},
"devDependencies": {
"#jest/globals": "^27.4.4",
"#types/express": "^4.17.13",
"#types/jest": "^27.4.0",
"#types/supertest": "^2.0.11",
"cross-env": "^7.0.3",
"supertest": "^6.2.1",
"ts-jest": "^27.1.3"
}
__tests__/setup.ts
import dotenv from 'dotenv';
dotenv.config({
path: './.env.test'
});
all is explained in the jest docs: jest docs
1.
npm install --save-dev babel-jest #babel/core #babel/preset-env
in file: babel.config.js
module.exports = {
presets: [['#babel/preset-env', {targets: {node: 'current'}}]],
};
In addition to installing babel-jest (which comes with Jest by default now) be sure to install regenerator-runtime.
To add support for React and react-testing-library it may be useful to eject CreateReactApp and take all needed Jest configuration from the package.json. It is ready to use with another bundler, Rollup in my case.

Webpack dev server configuration refuse to work with full path to index

Hello I am trying to understand why does webpack dev server refuse to work with full path to my index.js. (I am using webpack with babel to build reactJS.)
At the moment my webpack.config is located in the same directory as my index.js file and due to that the declaration of the entry point of my index.js is just "./index". Here is how my webpack.config looks like:
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: __dirname
}]
}};
With this configuration my project is build by babel and works just fine on the server!
My problem comes when I tried to specify a full path of my index.js entry point. I need that because I want to externalize the webpack and it's configuration from my FE code. To be sure that it will work I first tried not to rely that webpack.config and index.js are in the same directory but to specify the path of the index as full path name:
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'D:/projects/myProject/index'
]
With this config babel seem to be able to navigate to the index.js and start compiling it, but it does encounter an unexpected (for me) error during the parse:
ERROR in D:/projects/myProject/index.js
Module parse failed: D:/projects/myProject/index.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import 'babel-core/polyfill';
|
| import React from 'react';
# multi main
What do I miss, why webpack makes difference between relatively configured index.js and full path one?
(I made sure that the full path is correct)
Thanks!
After a bit annoying investigation it appeared that my problem is specifying the Windows drives in uppercase. For some reason it appear that the index.js location full path should start with lowercase drive letter!
Hopefully this experience may be helpful to others.
Try using:
d:/Folder1/folder2/index.js
instead of
D:/Folder1/folder2/index.js