what is the correct method to exclude node_modules from babel-Loader? in Rails/webpacker
Asked Answered
D

0

6

I encountered a "_typeof is not defined" error when I imported jstree.js with "rails/webpacker",i.e. Webpack in Rails6. This error seems to be caused by Babel. Babel defined _typeof function in front of source code of jstree.js and then replaced all typeof with _typeof . However, the _typeof function is regarded undefined.

I was told that it could be solved by setting exclude: /node_modules/ on babel-loader. I checked default configuration of babel-loader in file config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const babelLoader = environment.loaders.get('babel')
console.log(babelLoader);

result is :

test: /\.(js|jsx|mjs)?(\.erb)?$/,
include: [ '/home/demo/app_tree/app/javascript' ],
exclude: /node_modules/,
use: [ { loader: 'babel-loader', options: [Object] } ]

It seems that webpacker's default config file has excluded node_modules from babel-loader . Nothing could be done to fix it.

Finally I solved this error , thanks to guide here https://github.com/rails/webpacker/blob/54c3ca9245e9ee330f8ca63b447c202290f7b624/docs/v4-upgrade.md#excluding-node_modules-from-being-transpiled-by-babel-loader

Effecitve method is to delete "NodeModule" by adding following lines in file config/webpack/environment.js

const { environment } = require('@rails/webpacker')
environment.loaders.delete('nodeModules')

I am still confused although error is fixed . Why does "exclude: /node_modules/" attribute of babel-loader not work in this case? It looks exactly right according to official document of webpack. How does rails/webpacker map all configurations to file webpack.config.js ? Where can I review the file webpack.config.js which is eventually used by webpack?

Thank you !

Doran answered 19/8, 2020 at 5:43 Comment(1)
exclude: /node_modules/ doesn't work because webpacker adds another loader for babel with key: 'nodeModules' that has include: /node_modules/.Bharat

© 2022 - 2024 — McMap. All rights reserved.