Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[POC] Eject feature #1916

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions lib/eject/template.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Eject Webpacker
yes = yes? 'Are you sure you want to eject? This action is permanent. (y/N)'
return unless yes

loaders = Dir.glob("#{Rails.root.join('config/webpack/loaders')}/*")
.map { |loader|
basename = File.basename(loader, File.extname(loader))
"require('./loaders/#{basename}')"
}
webpacker_config = YAML.load_file(Rails.root.join('config/webpacker.yml'))

say 'Copying webpack.config.js'

File.write(Rails.root.join('config/webpack/webpack.config.js'), ERB.new(File.read("#{__dir__}/webpack.config.js.erb"), nil, '-').result(binding))

say "Installing all dependencies"

dependencies = %w[
webpack
webpack-cli
mini-css-extract-plugin
webpack-assets-manifest
case-sensitive-paths-webpack-plugin
pnp-webpack-plugin
babel-loader
]

run "yarn add #{dependencies.join(' ')}"

scripts = %Q(\n "start": "webpack --progress --watch --config config/webpack/webpack.config.js",\n "build": "NODE_ENV=production webpack --progress --config config/webpack/webpack.config.js")
npm_scripts = %Q("scripts": {#{scripts}\n },\n )

if File.foreach(Rails.root.join('package.json')).grep(/"scripts":\s+{/).any?
insert_into_file Rails.root.join("package.json").to_s, "#{scripts},", after: /"scripts":\s+{/
else
insert_into_file Rails.root.join("package.json").to_s, npm_scripts, before: /"dependencies":\s+{/
end

remove_file "#{Rails.root.join('config/webpacker.yml')}"
copy_file "#{__dir__}/webpacker.yml", "#{Rails.root.join('config/webpacker.yml')}"

# Remove files
remove_file "#{Rails.root.join('config/webpack/development.js')}"
remove_file "#{Rails.root.join('config/webpack/test.js')}"
remove_file "#{Rails.root.join('config/webpack/production.js')}"
remove_file "#{Rails.root.join('config/webpack/environment.js')}"
remove_file "#{Rails.root.join('bin/webpack')}"
remove_file "#{Rails.root.join('bin/webpack-dev-server')}"

say "Webpacker successfully ejected 🎉 🍰", :green
188 changes: 188 additions & 0 deletions lib/eject/webpack.config.js.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<%- config = webpacker_config['development'] -%>
const glob = require('glob');
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const WebpackAssetsManifest = require('webpack-assets-manifest')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const PnpWebpackPlugin = require('pnp-webpack-plugin')

const packs = path.join(__dirname, '..', '..', 'app', 'javascript', 'packs');
const targets = glob.sync(path.join(packs, '**/*.{js,jsx,ts,tsx}'))

const nodeEnv = process.env.NODE_ENV || 'development';

const inDevServer = process.argv.find(v => v.includes('webpack-dev-server'))
const isHMR = inDevServer && (devServer && devServer.hmr)

const styleLoader = {
loader: 'style-loader',
options: {
hmr: isHMR,
sourceMap: true
}
}

const getStyleRule = (test, modules = false, preprocessors = []) => {
const use = [
{
loader: 'css-loader',
options: {
sourceMap: true,
importLoaders: 2,
localIdentName: '[name]__[local]___[hash:base64:5]',
modules
}
},
{
loader: 'postcss-loader',
options: {
config: { path: path.resolve() },
sourceMap: true
}
},
...preprocessors
]

const options = modules ? { include: /\.module\.[a-z]+$/ } : { exclude: /\.module\.[a-z]+$/ }

if (nodeEnv === 'production') {
use.unshift(MiniCssExtractPlugin.loader)
} else {
use.unshift(styleLoader)
}

// sideEffects - See https://github.com/webpack/webpack/issues/6571
return {
...{ test, use, sideEffects: !modules },
...options,
}
}

const entry = targets.reduce((acc, target) => {
const bundle = path.relative(packs, target)
const ext = path.extname(bundle)
return {
...acc,
...{ [bundle.replace(ext, '')]: './app/javascript/packs/' + bundle },
}
}, {})

module.exports = {
mode: nodeEnv === "development" ? 'development' : 'production',
entry,
output: {
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].chunk.js',
hotUpdateChunkFilename: '[id]-[hash].hot-update.js',
path: path.join(__dirname, '..', '..', 'public', 'packs'),
publicPath: '/packs/',
pathinfo: true
},
resolve: {
extensions: <%= config['extensions'] %>,
plugins: [PnpWebpackPlugin],
modules: [
path.resolve('<%= config['source_path'] %>'),
<%- config['resolved_paths'].each do |path| -%>
path.resolve('<%= path %>'),
<%- end -%>
'node_modules',
]
},
cache: true,
devtool: 'cheap-module-source-map',
devServer: <%= config['dev_server'].to_json %>,
module: {
strictExportPresence: true,
rules: [
{ parser: { requireEnsure: false } },
{
test: new RegExp(/<%= config['static_assets_extensions'].join('|') %>/, 'i'),
use: [
{
loader: 'file-loader',
options: {
name: '[path][name]-[hash].[ext]',
context: path.join('<%= config['source_path'] %>')
}
}
]
},
{
test: /\.(js|jsx|mjs)?(\.erb)?$/,
include: path.resolve('<%= config['source_path'] %>'),
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: path.join('<%= config['cache_path'] %>', 'babel-loader-node-modules'),
cacheCompression: nodeEnv === 'production',
compact: nodeEnv === 'production'
}
}
]
},
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['@babel/preset-env', { modules: false }]],
cacheDirectory: path.join('<%= config['cache_path'] %>', 'babel-loader-node-modules'),
cacheCompression: nodeEnv === 'production',
compact: false,
sourceMaps: false
}
}
]
},
getStyleRule(/\.(css)$/i),
getStyleRule(/\.(css)$/i, true),
getStyleRule(/\.(scss|sass)$/i, true, [
{
loader: 'sass-loader',
options: { sourceMap: true }
}
]),
getStyleRule(/\.(scss|sass)$/i, true, [
{
loader: 'sass-loader',
options: { sourceMap: true }
}
]),
<%- loaders.each do |loader| -%>
<%= loader %>,
<%- end -%>
],
},
resolveLoader: {
modules: ['node_modules'],
plugins: [PnpWebpackPlugin.moduleLoader(module)]
},
plugins: [
new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))),
new CaseSensitivePathsPlugin(),
new MiniCssExtractPlugin({
filename: '[name]-[contenthash:8].css',
chunkFilename: '[name]-[contenthash:8].chunk.css'
}),
new WebpackAssetsManifest({
integrity: false,
entrypoints: true,
writeToDisk: true,
publicPath: true
}),
],
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
},
}
8 changes: 8 additions & 0 deletions lib/eject/webpacker.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
default: &default
compile: false
development:
<<: *default
test:
<<: *default
production:
<<: *default
13 changes: 13 additions & 0 deletions lib/tasks/webpacker/eject.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
eject_template_path = File.expand_path("../../eject/template.rb", __dir__).freeze
bin_path = ENV["BUNDLE_BIN"] || "./bin"

namespace :webpacker do
desc "Eject Webpacker binstubs in this application"
task :eject do
if Rails::VERSION::MAJOR >= 5
exec "#{RbConfig.ruby} #{bin_path}/rails app:template LOCATION=#{eject_template_path}"
else
exec "#{RbConfig.ruby} #{bin_path}/rake rails:template LOCATION=#{eject_template_path}"
end
end
end
1 change: 1 addition & 0 deletions test/rake_tasks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def test_rake_tasks
assert_includes output, "webpacker:install:react"
assert_includes output, "webpacker:install:vue"
assert_includes output, "webpacker:verify_install"
assert_includes output, "webpacker:eject"
end

def test_rake_task_webpacker_check_binstubs
Expand Down