refactor: migrate from browserify to webpack (#4764)

Co-authored-by: HashimotoYT <hashimoto.stream@gmail.com>
This commit is contained in:
Nastya Antonenko 2021-01-08 11:36:33 -08:00 коммит произвёл GitHub
Родитель 50ac32cc32
Коммит ed7a270a73
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
12 изменённых файлов: 3102 добавлений и 1104 удалений

10
.babelrc Normal file
Просмотреть файл

@ -0,0 +1,10 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": "> 0.25%, not dead"
}
]
]
}

Просмотреть файл

@ -1,23 +0,0 @@
const nodeModulesToAvoidBabelifying = ['lodash', 'lunr', 'prettydate']
const excludeRegex = new RegExp(
`/node_modules/(${nodeModulesToAvoidBabelifying.join('|')})`
)
module.exports = function doBrowserify(browserify) {
return function (entry) {
return browserify(entry, {
transform: [
[
'babelify',
{
global: true,
exclude: excludeRegex,
presets: [['@babel/preset-env', { targets: '> 0.25%, not dead' }]],
},
],
'brfs',
],
})
}
}

Просмотреть файл

@ -1,4 +0,0 @@
const browserify = require('browserify-middleware')
const browserifyOptions = require('./browserify-opts')
module.exports = browserifyOptions(browserify)

9
middleware/webpack.js Normal file
Просмотреть файл

@ -0,0 +1,9 @@
const webpack = require('webpack')
const config = require('../webpack.common')
const webpackDevMiddleware = require('webpack-dev-middleware')
module.exports = () => {
return webpackDevMiddleware(webpack(config), {
publicPath: config.output.publicPath,
})
}

4033
package-lock.json сгенерированный

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -15,7 +15,7 @@
"release": "node script/release",
"dev": "cross-env NODE_PATH=. NODE_ENV=development nodemon server.js",
"prepack": "check-for-leaks",
"precompile-assets": "cross-env NODE_ENV=production node script/precompile-assets.js",
"precompile-assets": "cross-env NODE_ENV=production webpack --config ./webpack.common.js && node script/precompile-assets.js",
"linkschecker": "NODE_PATH=. NODE_ENV=test node scripts/links-checker.js",
"cypress": "cypress run",
"lint": "npm run lint:js && npm run lint:style",
@ -35,10 +35,7 @@
"@primer/css": "^15.2.0",
"@primer/octicons": "^11.1.0",
"awesome-electron": "2.6.0",
"babelify": "^10.0.0",
"brfs": "^2.0.2",
"browser-date-formatter": "^3.0.3",
"browserify-middleware": "^8.1.1",
"clipboard": "^2.0.6",
"compression": "^1.7.4",
"connect-browser-sync": "^2.1.0",
@ -91,6 +88,7 @@
},
"devDependencies": {
"browser-sync": "^2.26.13",
"babel-loader": "^8.1.0",
"chai": "^4.2.0",
"chai-cheerio": "^1.0.0",
"check-for-leaks": "^1.2.1",
@ -102,6 +100,7 @@
"husky": "^4.3.0",
"lint-staged": "^10.5.2",
"mocha": "^8.2.1",
"handlebars-loader": "^1.7.1",
"nock": "^13.0.4",
"node-sass": "^5.0.0",
"nodemon": "^2.0.7",
@ -112,9 +111,11 @@
"stylelint-scss": "^3.18.0",
"supertest": "^5.0.0",
"supertest-session": "^4.1.0",
"uglify-js": "^3.12.0",
"wait-on": "^5.2.1",
"walk-sync": "^2.2.0"
"walk-sync": "^2.2.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-middleware": "^3.7.2"
},
"engines": {
"node": ">=12 <14"

Просмотреть файл

@ -1,41 +1,16 @@
const path = require('path')
const stream = require('stream')
const fs = require('fs-extra')
const browserify = require('browserify')
const browserifyOptions = require('../middleware/browserify-opts')
const sass = require('node-sass')
const uglify = require('uglify-js')
function dir(...parts) {
return path.join(__dirname, '..', ...parts)
}
function uglifyStream() {
const buffers = []
return new stream.Transform({
transform(chunk, _encoding, callback) {
buffers.push(chunk)
callback()
},
flush(callback) {
const code = Buffer.concat(buffers).toString()
const compiled = uglify.minify(code)
this.push(compiled.code)
callback()
},
})
}
const PATHS = {
precompiled: dir('precompiled'),
scripts: dir('precompiled', 'scripts'),
styles: dir('precompiled', 'styles'),
nodeModules: dir('node_modules'),
jsEntry: dir('scripts', 'index.js'),
jsDestination: dir('precompiled', 'scripts', 'index.js'),
cssEntry: dir('public', 'styles', 'index.scss'),
cssDestination: dir('precompiled', 'styles', 'index.css'),
}
@ -43,11 +18,7 @@ const PATHS = {
async function precompileAssets() {
try {
console.log('Creating directories...')
await fs.remove(PATHS.precompiled)
await fs.ensureDir(PATHS.scripts)
await fs.ensureDir(PATHS.styles)
console.log('Precompiling JS...')
await precompileJavaScript()
console.log('Precompiling CSS...')
await precompileCss()
} catch (err) {
@ -56,18 +27,6 @@ async function precompileAssets() {
}
}
function precompileJavaScript() {
return new Promise((resolve, reject) => {
const b = browserifyOptions(browserify)(PATHS.jsEntry)
const pipe = b
.bundle()
.pipe(uglifyStream())
.pipe(fs.createWriteStream(PATHS.jsDestination))
pipe.on('error', reject)
pipe.on('finish', resolve)
})
}
function precompileCss() {
return new Promise((resolve, reject) => {
sass.render(

Просмотреть файл

@ -1,5 +1,7 @@
import search from './search'
document.addEventListener('DOMContentLoaded', () => {
require('./search')()
search()
require('./lazy-load-images')()
require('./get-localized-strings')()
require('./create-filter-list')()

Просмотреть файл

@ -1,5 +1,6 @@
const templates = require('../templates')
const instantsearch = require('instantsearch.js')
import instantsearch from 'instantsearch.js'
import { searchBox, hits } from 'instantsearch.js/es/widgets'
const pluralize = require('pluralize')
const searchWithYourKeyboard = require('search-with-your-keyboard')
const searches = {}
@ -23,7 +24,7 @@ const types = [
]
const typeNames = types.map((type) => type.name)
module.exports = () => {
export default () => {
buildMultiSearch()
buildSearchUIHandlers()
determineOrder()
@ -107,7 +108,7 @@ function buildSearch(type, isPrimarySearch = false, searches) {
const search = instantsearch(opts)
search.addWidget(
instantsearch.widgets.hits({
hits({
container: `#${type}-hits`,
templates: {
// empty: 'No results',
@ -125,7 +126,7 @@ function buildSearch(type, isPrimarySearch = false, searches) {
if (isPrimarySearch) {
search.addWidget(
instantsearch.widgets.searchBox({
searchBox({
container: '#search-input',
placeholder: `Search Electron ${pluralize(type)}`,
autofocus: false,

Просмотреть файл

@ -12,7 +12,6 @@ const useragent = require('express-useragent')
const compression = require('compression')
const slashes = require('connect-slashes')
const browsersync = require('./middleware/browsersync')
const browserify = require('./middleware/browserify')
const requestLanguage = require('express-request-language')
const cookieParser = require('cookie-parser')
const sass = require('./middleware/sass')
@ -82,10 +81,13 @@ if (process.env.NODE_ENV === 'production') {
app.use(
express.static(path.join(__dirname, 'precompiled'), { redirect: false })
)
} else {
} else if (process.env.NODE_ENV === 'development') {
console.log('Dev app detected; compiling JS and CSS in memory')
app.use(sass())
app.use('/scripts/index.js', browserify('scripts/index.js'))
const webpack = require('./middleware/webpack')
app.use(webpack())
} else {
app.use(sass())
}
app.get('/service-worker.js', (req, res) =>
res.sendFile(path.resolve(__dirname, 'scripts', 'service-worker.js'))

Просмотреть файл

@ -1,14 +1,6 @@
const fs = require('fs')
const path = require('path')
// This module gets browserified with the `brfs` transform.
// Since brfs evaluates source code statically, you can't use dynamic
// expressions that need to be evaluated at runtime.
// See https://github.com/browserify/brfs#gotchas
module.exports = {
app: fs.readFileSync(path.join(__dirname, 'app.hbs'), 'utf8'),
api: fs.readFileSync(path.join(__dirname, 'api.hbs'), 'utf8'),
package: fs.readFileSync(path.join(__dirname, 'package.hbs'), 'utf8'),
tutorial: fs.readFileSync(path.join(__dirname, 'tutorial.hbs'), 'utf8'),
app: require('./app.hbs'),
api: require('./api.hbs'),
package: require('./package.hbs'),
tutorial: require('./tutorial.hbs'),
}

36
webpack.common.js Normal file
Просмотреть файл

@ -0,0 +1,36 @@
const path = require('path')
const env = process.env.NODE_ENV
module.exports = {
entry: { index: './scripts/index.js' },
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'precompiled', 'scripts'),
publicPath: '/scripts/',
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.hbs$/,
loader: 'handlebars-loader',
},
],
},
devtool: env === 'production' ? 'inline-source-map' : 'source-map',
mode: env === 'production' ? 'production' : 'development',
}