feat(assets): use vitejs to build javascript

This commit is contained in:
Paul Chavard 2022-02-24 08:59:32 +00:00
parent 43be4482ee
commit 187e84a010
38 changed files with 656 additions and 4038 deletions

View file

@ -1,10 +0,0 @@
> 1%
Chrome >= 50
Edge >= 14
Firefox >= 50
Opera >= 40
Safari >= 8
iOS >= 8
# Although IE 11 shows a deprecation banner, we still support the transpilation option.
# IE 11 support will be removed on Jan. 31st, 2021.
IE >= 11

View file

@ -1,10 +1,6 @@
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
parser: '@typescript-eslint/parser',
globals: {
process: true,
gon: true
@ -27,25 +23,15 @@ module.exports = {
'react/prop-types': 'off'
},
settings: {
react: {
version: 'detect'
}
react: { version: 'detect' }
},
overrides: [
{
files: [
'.eslintrc.js',
'config/webpack/**/*.js',
'babel.config.js',
'postcss.config.js'
],
env: {
node: true
}
files: ['.eslintrc.js', 'vite.config.ts'],
env: { node: true }
},
{
files: ['**/*.ts', '**/*.tsx'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',

View file

@ -105,7 +105,7 @@ jobs:
run: |
SPEC_FILES=$(./split_tests -glob='spec/system/**/*_spec.rb' -split-index=${{ strategy.job-index }} -split-total=${{ strategy.job-total }} -junit -junit-path=tmp/*.junit.xml)
echo "Running tests for bin/rspec $SPEC_FILES"
bin/rspec $SPEC_FILES --format progress --format RspecJunitFormatter --out tmp/rspec_${{ github.job }}_${{ strategy.job-index }}.junit.xml
RAILS_ENV=test bin/rspec $SPEC_FILES --format progress --format RspecJunitFormatter --out tmp/rspec_${{ github.job }}_${{ strategy.job-index }}.junit.xml
- name: Upload test results for this instance
uses: actions/upload-artifact@v2

11
.gitignore vendored
View file

@ -19,10 +19,7 @@ doc/*.svg
uploads/*
.byebug_history
.env
Procfile.dev
storage/
/public/packs
/public/packs-test
/node_modules
/yarn-error.log
yarn-debug.log*
@ -42,3 +39,11 @@ yarn-debug.log*
# Custom views
/app/custom_views/*
!/app/custom_views/.keep
# Webpacker
public/packs
public/packs-test
# Vite Ruby
public/vite
public/vite-dev
public/vite-test

View file

@ -82,8 +82,9 @@ gem 'skylight'
gem 'spreadsheet_architect'
gem 'strong_migrations' # lint database migrations
gem 'typhoeus'
gem 'vite_plugin_legacy'
gem 'vite_rails'
gem 'warden'
gem 'webpacker'
gem 'zipline'
gem 'zxcvbn-ruby', require: 'zxcvbn'

View file

@ -217,6 +217,7 @@ GEM
dotenv-rails (2.7.6)
dotenv (= 2.7.6)
railties (>= 3.2)
dry-cli (0.7.0)
dry-inflector (0.2.0)
dumb_delegator (1.0.0)
ecma-re-validator (0.3.0)
@ -498,7 +499,7 @@ GEM
rack (>= 2.1.0)
rack-protection (2.1.0)
rack
rack-proxy (0.7.0)
rack-proxy (0.7.2)
rack
rack-test (1.1.0)
rack (>= 1.0, < 3)
@ -647,7 +648,6 @@ GEM
selenium-webdriver (3.142.7)
childprocess (>= 0.5, < 4.0)
rubyzip (>= 1.2.2)
semantic_range (3.0.0)
sentry-delayed_job (4.8.1)
delayed_job (>= 4.0)
sentry-ruby-core (~> 4.8.1)
@ -726,6 +726,15 @@ GEM
axiom-types (~> 0.1)
coercible (~> 1.0)
descendants_tracker (~> 0.0, >= 0.0.3)
vite_plugin_legacy (3.0.2)
vite_ruby (~> 3.0, >= 3.0.4)
vite_rails (3.0.6)
railties (>= 5.1, < 8)
vite_ruby (~> 3.0)
vite_ruby (3.0.9)
dry-cli (~> 0.7.0)
rack-proxy (~> 0.6, >= 0.6.1)
zeitwerk (~> 2.2)
warden (1.2.9)
rack (>= 2.0.9)
watir (6.19.1)
@ -747,11 +756,6 @@ GEM
addressable (>= 2.3.6)
crack (>= 0.3.2)
hashdiff (>= 0.4.0, < 2.0.0)
webpacker (5.4.3)
activesupport (>= 5.2)
rack-proxy (>= 0.6.1)
railties (>= 5.2)
semantic_range (>= 2.3.0)
websocket-driver (0.7.5)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.5)
@ -881,11 +885,12 @@ DEPENDENCIES
timecop
typhoeus
vcr
vite_plugin_legacy
vite_rails
warden
web-console
webdrivers (~> 4.0)
webmock
webpacker
zipline
zxcvbn-ruby

View file

@ -1,2 +0,0 @@
server: RAILS_QUEUE_ADAPTER=delayed_job bin/rails server -p 3000
jobs: bin/rake jobs:work

3
Procfile.dev Normal file
View file

@ -0,0 +1,3 @@
web: RAILS_QUEUE_ADAPTER=delayed_job bin/rails server -p 3000
jobs: bin/rake jobs:work
vite: bin/vite dev

View file

@ -1,7 +1,6 @@
import '../shared/polyfills';
import Rails from '@rails/ujs';
import * as ActiveStorage from '@rails/activestorage';
import 'whatwg-fetch'; // window.fetch polyfill
import '../shared/page-update-event';
import '../shared/activestorage/ujs';
@ -96,8 +95,10 @@ const DS = {
};
// Start Rails helpers
Rails.start();
ActiveStorage.start();
// Expose globals
window.DS = window.DS || DS;
import('../shared/track/matomo');
import('../shared/track/sentry');

View file

@ -1,4 +1,4 @@
import { scrollTo, scrollToBottom } from '@utils';
import { scrollToElement, scrollToBottom } from '@utils';
function scrollMessagerie() {
const ul = document.querySelector('.messagerie ul');
@ -7,7 +7,7 @@ function scrollMessagerie() {
const elementToScroll = document.querySelector('.date.highlighted');
if (elementToScroll) {
scrollTo(ul, elementToScroll);
scrollToElement(ul, elementToScroll);
} else {
scrollToBottom(ul);
}

View file

@ -1,2 +0,0 @@
import '../shared/track/matomo';
import '../shared/track/sentry';

View file

@ -2,7 +2,6 @@ const fconnect = {
tracesUrl: '/traces',
aboutUrl: ''
};
const document = window.document;
function init() {
fconnect.currentHost = 'fcp.integ01.dev-franceconnect.fr';

View file

@ -2,7 +2,6 @@
// Due to babel.config.js's 'useBuiltIns', only polyfills actually
// required by the browsers we support will be included.
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import 'dom4';
import 'intersection-observer';
import 'whatwg-fetch';

View file

@ -111,7 +111,7 @@ export function getJSON(url: string, data: unknown, method = 'GET') {
});
}
export function scrollTo(container: HTMLElement, scrollTo: HTMLElement) {
export function scrollToElement(container: HTMLElement, scrollTo: HTMLElement) {
container.scrollTop =
offset(scrollTo).top - offset(container).top + container.scrollTop;
}

View file

@ -1,6 +1,5 @@
class BrowserSupport
def self.supported?(browser)
# See .browserslistrc
[
browser.chrome? && browser.version.to_i >= 50 && !browser.platform.ios?,
browser.edge? && browser.version.to_i >= 14 && !browser.compatibility_view?,

View file

@ -13,8 +13,11 @@
= favicon_link_tag(image_url("#{FAVICON_32PX_SRC}"), type: "image/png", sizes: "32x32")
= favicon_link_tag(image_url("#{FAVICON_96PX_SRC}"), type: "image/png", sizes: "96x96")
- packs = ['application', 'track', administrateur_signed_in? ? 'track-admin' : nil].compact
= javascript_packs_with_chunks_tag *packs, defer: true
= vite_client_tag
= vite_react_refresh_tag
= vite_javascript_tag 'application'
- if administrateur_signed_in?
= vite_javascript_tag 'track-admin'
= preload_link_tag(asset_url("Muli-Regular.woff2"))
= preload_link_tag(asset_url("Muli-Bold.woff2"))
@ -40,4 +43,6 @@
- if content_for?(:footer)
= content_for(:footer)
= vite_legacy_javascript_tag 'application'
= yield :charts_js

View file

@ -11,7 +11,7 @@ by providing a `content_for(:javascript)` block.
<%= javascript_include_tag js_path %>
<% end %>
<%= javascript_packs_with_chunks_tag 'manager' %>
<%= vite_javascript_tag 'manager' %>
<%= yield :javascript %>

View file

@ -1,97 +0,0 @@
module.exports = function (api) {
var validEnv = ['development', 'test', 'production'];
var currentEnv = api.env();
var isDevelopmentEnv = api.env('development');
var isProductionEnv = api.env('production');
var isTestEnv = api.env('test');
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
);
}
return {
presets: [
isTestEnv && [
'@babel/preset-env',
{
targets: {
node: 'current'
}
}
],
(isProductionEnv || isDevelopmentEnv) && [
'@babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'usage',
corejs: 3,
modules: false,
exclude: ['transform-typeof-symbol']
}
],
[
'@babel/preset-react',
{
development: isDevelopmentEnv || isTestEnv,
useBuiltIns: true
}
],
['@babel/preset-typescript', { allExtensions: true, isTSX: true }]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'@babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'@babel/plugin-transform-destructuring',
[
'@babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'@babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'@babel/plugin-proposal-private-methods',
{
loose: true
}
],
[
'@babel/plugin-proposal-private-property-in-object',
{
loose: true
}
],
[
'@babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true
}
],
[
'@babel/plugin-transform-regenerator',
{
async: false
}
],
isProductionEnv && [
'babel-plugin-transform-react-remove-prop-types',
{
removeImport: true
}
]
].filter(Boolean)
};
};

9
bin/dev Executable file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env bash
if ! command -v foreman &> /dev/null
then
echo "Installing foreman..."
gem install foreman
fi
foreman start -f Procfile.dev "$@"

29
bin/vite Executable file
View file

@ -0,0 +1,29 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'vite' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
bundle_binstub = File.expand_path("../bundle", __FILE__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("vite_ruby", "vite")

View file

@ -1,18 +0,0 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"] ||= "development"
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
require "bundler/setup"
require "webpacker"
require "webpacker/webpack_runner"
APP_ROOT = File.expand_path("..", __dir__)
Dir.chdir(APP_ROOT) do
Webpacker::WebpackRunner.run(ARGV)
end

View file

@ -1,18 +0,0 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"] ||= "development"
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
Pathname.new(__FILE__).realpath)
require "bundler/setup"
require "webpacker"
require "webpacker/dev_server_runner"
APP_ROOT = File.expand_path("..", __dir__)
Dir.chdir(APP_ROOT) do
Webpacker::DevServerRunner.run(ARGV)
end

View file

@ -3,9 +3,6 @@ require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = true
# In the development environment your application's code is reloaded any time
# it changes. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.

View file

@ -4,9 +4,6 @@ require Rails.root.join("app/lib/balancer_delivery_method")
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = false
# Code is not reloaded between requests.
config.cache_classes = true

View file

@ -44,6 +44,11 @@ Rails.application.config.content_security_policy do |policy|
# Allow LiveReload requests
policy.connect_src(*policy.connect_src, "ws://localhost:3035", "http://localhost:3035")
# Allow Vite.js
policy.connect_src(*policy.connect_src, "ws://#{ViteRuby.config.host_with_port}")
policy.script_src(*policy.script_src, :unsafe_eval, "http://#{ViteRuby.config.host_with_port}")
policy.style_src(*policy.style_src, :unsafe_inline)
# CSP are not enforced in development (see content_security_policy_report_only in development.rb)
# However we notify a random local URL, to see breakage in the DevTools when adding a new external resource.
policy.report_uri "http://#{ENV.fetch('APP_HOST')}/csp/"
@ -52,7 +57,7 @@ Rails.application.config.content_security_policy do |policy|
# Disallow all connections to external domains during tests
policy.img_src(:self, :data, :blob)
policy.script_src(:self, :unsafe_eval, :unsafe_inline, :blob)
policy.style_src(:self)
policy.style_src(:self, :unsafe_inline)
policy.connect_src(:self)
policy.frame_src(:self)
policy.default_src(:self, :data, :blob)

16
config/vite.json Normal file
View file

@ -0,0 +1,16 @@
{
"all": {
"sourceCodeDir": "app/javascript",
"watchAdditionalPaths": []
},
"development": {
"autoBuild": true,
"publicOutputDir": "vite-dev",
"port": 3036
},
"test": {
"autoBuild": true,
"publicOutputDir": "vite-test",
"port": 3037
}
}

View file

@ -1,5 +0,0 @@
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const environment = require('./environment');
module.exports = environment.toWebpackConfig();

View file

@ -1,34 +0,0 @@
const path = require('path');
const { environment } = require('@rails/webpacker');
const resolve = {
alias: {
'@utils': path.resolve(__dirname, '..', '..', 'app/javascript/shared/utils')
}
};
environment.splitChunks();
environment.config.merge({ resolve });
// Excluding node_modules From Being Transpiled By Babel-Loader
// One change to take into consideration,
// is that Webpacker 4 transpiles the node_modules folder with the babel-loader.
// This folder used to be ignored by Webpacker 3.
// The new behavior helps in case some library contains ES6 code, but in some cases it can lead to issues.
// To avoid running babel-loader in the node_modules folder, replicating the same behavior as Webpacker 3,
// we added the following code:
const nodeModulesLoader = environment.loaders.get('nodeModules');
if (!Array.isArray(nodeModulesLoader.exclude)) {
nodeModulesLoader.exclude =
nodeModulesLoader.exclude == null ? [] : [nodeModulesLoader.exclude];
}
nodeModulesLoader.exclude.push(
path.resolve(__dirname, '..', '..', 'node_modules/maplibre-gl')
);
// Uncoment next lines to run webpack-bundle-analyzer
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
// environment.plugins.append('BundleAnalyzer', new BundleAnalyzerPlugin());
module.exports = environment;

View file

@ -1,5 +0,0 @@
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const environment = require('./environment');
module.exports = environment.toWebpackConfig();

View file

@ -1,5 +0,0 @@
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const environment = require('./environment');
module.exports = environment.toWebpackConfig();

View file

@ -1,95 +0,0 @@
# Note: You must restart bin/webpack-dev-server for changes to take effect
default: &default
source_path: app/javascript
source_entry_path: packs
public_root_path: public
public_output_path: packs
cache_path: tmp/cache/webpacker
webpack_compile_output: false
# Additional paths webpack should lookup modules
# ['app/assets', 'engine/foo/app/assets']
additional_paths: []
# Reload manifest.json on all requests so we reload latest compiled packs
cache_manifest: false
# Extract and emit a css file
extract_css: false
static_assets_extensions:
- .jpg
- .jpeg
- .png
- .gif
- .tiff
- .ico
- .svg
- .eot
- .otf
- .ttf
- .woff
- .woff2
extensions:
- .tsx
- .ts
- .mjs
- .js
- .jsx
- .sass
- .scss
- .css
- .module.sass
- .module.scss
- .module.css
- .png
- .svg
- .gif
- .jpeg
- .jpg
development:
<<: *default
compile: true
# Reference: https://webpack.js.org/configuration/dev-server/
dev_server:
https: false
host: localhost
port: 3035
public: localhost:3035
hmr: false
# Inline should be set to true if using HMR
inline: true
overlay: true
compress: true
disable_host_check: true
use_local_ip: false
quiet: false
pretty: false
headers:
'Access-Control-Allow-Origin': '*'
watch_options:
ignored: '**/node_modules/**'
test:
<<: *default
compile: true
# Compile test packs to a separate directory
public_output_path: packs-test
production:
<<: *default
# Production depends on precompilation of packs prior to booting for performance.
compile: false
# Extract and emit a css file
extract_css: true
# Cache manifest.json for performance
cache_manifest: true

View file

@ -1,7 +1,5 @@
{
"dependencies": {
"@babel/preset-react": "^7.14.5",
"@babel/preset-typescript": "^7.16.7",
"@headlessui/react": "^1.3.0",
"@heroicons/react": "^1.0.1",
"@mapbox/mapbox-gl-draw": "^1.3.0",
@ -9,14 +7,11 @@
"@rails/actiontext": "^6.1.4-1",
"@rails/activestorage": "^6.1.4-1",
"@rails/ujs": "^6.1.4-1",
"@rails/webpacker": "5.4.3",
"@reach/auto-id": "^0.16.0",
"@reach/combobox": "^0.13.0",
"@reach/slider": "^0.15.0",
"@sentry/browser": "6.12.0",
"@tmcw/togeojson": "^4.3.0",
"babel-plugin-macros": "^2.8.0",
"babel-plugin-transform-react-remove-prop-types": "^0.4.24",
"chartkick": "^3.2.0",
"core-js": "^3.6.5",
"debounce": "^1.2.1",
@ -39,8 +34,6 @@
"tiny-invariant": "^1.2.0",
"trix": "^1.2.3",
"use-debounce": "^5.2.0",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"whatwg-fetch": "^3.0.0"
},
"devDependencies": {
@ -54,8 +47,10 @@
"@types/react-dom": "^17.0.11",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
"babel-eslint": "^10.1.0",
"del-cli": "^4.0.1",
"@vitejs/plugin-legacy": "^1.2.3",
"@vitejs/plugin-react": "^1.1.4",
"@vitejs/plugin-react-refresh": "^1.3.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
@ -64,12 +59,13 @@
"netlify-cli": "^8.3.0",
"prettier": "^2.3.2",
"typescript": "^4.5.5",
"webpack-bundle-analyzer": "^3.7.0",
"webpack-dev-server": "^4.6.0"
"vite": "^2.7.13",
"vite-plugin-full-reload": "^1.0.0",
"vite-plugin-ruby": "^3.0.8"
},
"scripts": {
"clean": "del tmp public/packs public/packs-test",
"lint:js": "eslint --ext .js,.jsx,.ts,.tsx ./app/javascript ./config/webpack",
"clean": "del tmp public/packs public/packs-test public/vite public/vite-dev public/vite-test node_modules/.vite",
"lint:js": "eslint --ext .js,.jsx,.ts,.tsx ./app/javascript",
"webpack:build": "NODE_ENV=production bin/webpack",
"lint:types": "tsc",
"graphql:docs:build": "graphdoc --force",
@ -77,7 +73,7 @@
"graphql:docs:publish": "yarn graphql:docs:build && yarn graphql:docs:deploy"
},
"engines": {
"node": ">= 12.*"
"node": ">= 14.*"
},
"graphdoc": {
"endpoint": "https://www.demarches-simplifiees.fr/api/v2/graphql",

View file

@ -1,12 +0,0 @@
module.exports = {
plugins: [
require('postcss-import'),
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
})
]
}

View file

@ -1,27 +1,22 @@
{
"include": ["app/javascript/**/*.ts", "app/javascript/**/*.tsx"],
"compilerOptions": {
"declaration": false,
"experimentalDecorators": true,
"lib": ["DOM", "DOM.Iterable", "ES2019"],
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"target": "ES2019",
"moduleResolution": "node",
"module": "ES6",
"jsx": "react",
"noEmit": true,
"skipLibCheck": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"isolatedModules": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"paths": {
"~/*": ["./app/javascript/*"],
"@utils": ["./app/javascript/shared/utils.ts"]
}
},
"exclude": [
"**/*.spec.ts",
"node_modules",
"vendor",
"public"
],
"compileOnSave": false
"noEmit": true
}
}

33
vite.config.ts Normal file
View file

@ -0,0 +1,33 @@
import { defineConfig } from 'vite';
import ViteReact from '@vitejs/plugin-react';
import ViteLegacy from '@vitejs/plugin-legacy';
import FullReload from 'vite-plugin-full-reload';
import RubyPlugin from 'vite-plugin-ruby';
export default defineConfig({
resolve: { alias: { '@utils': '/shared/utils.ts' } },
build: {
sourcemap: true,
rollupOptions: {
output: {
manualChunks(id) {
if (id.match('maplibre') || id.match('mapbox')) {
return 'maplibre';
}
}
}
}
},
plugins: [
RubyPlugin(),
ViteReact({
parserPlugins: ['classProperties', 'classPrivateProperties'],
jsxRuntime: 'classic'
}),
FullReload(['config/routes.rb', 'app/views/**/*'], { delay: 200 }),
ViteLegacy({
targets: ['defaults', 'IE >= 11'],
additionalLegacyPolyfills: ['regenerator-runtime/runtime']
})
]
});

4155
yarn.lock

File diff suppressed because it is too large Load diff