javascript - 禁用 Babel 中忽略的目录“node_modules”
问题描述
我使用 webpack4 + babel7。在我的 JS 脚本中,我需要导入 NPM 模块。该模块使用 ES6 类和模块。并且在构建捆绑这个类之后不会转换为标准函数。如何让我需要的 NPM 模块被完全转译?
包.json
{
"scripts": {
"dev": "webpack --config webpack.config.js --mode=development",
"prod": "webpack --config webpack.config.js --mode=production"
},
"dependencies": {
"@betakiller/wamp-wrapper": "^0.1.0",
"babel-polyfill": "^6.26.0",
"chalk": "^2.4.1",
"whatwg-fetch": "^3.0.0"
},
"devDependencies": {
"@babel/cli": "^7.1.2",
"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"babel-loader": "^8.0.4",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
}
}
webpack.config.js
const path = require('path');
const paths = {
'src': __dirname,
'dist': path.resolve(__dirname, 'dist')
};
module.exports = {
entry: {
app: paths.src + '/app.js'
},
output: {
filename: '[name].js',
path: paths.dist
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader'
}
]
}
};
.babelrc
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"forceAllTransforms":true
}
]
]
}
应用程序.js
console.log('app.js');
import BetakillerWampFacade from '@betakiller/wamp-wrapper';
import ImportedClass from './ImportedClass';
const WampFacade = new BetakillerWampFacade();
console.log('WampFacade', WampFacade);
const Imported = new ImportedClass();
console.log('Imported', Imported);
导入类.js
'use strict';
export default class ImportedClass {
action(){
console.log('ImportedClass');
}
}
webpack.config.js 中的测试失败
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules\/(?!@betakiller\/wamp-wrappe).*/
}
]
}
我的解决方案
- 将 babel 配置移动到 webpack 配置
- 消除
.babelrc
新的 webpack.config.js
const path = require('path');
const paths = {
'src': __dirname,
'dist': path.resolve(__dirname, 'dist')
};
module.exports = {
entry: {
app: paths.src + '/app.js'
},
output: {
filename: '[name].js',
path: paths.dist
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
ignore: [],
presets: [
[
"@babel/preset-env",
{
forceAllTransforms: true
}
]
]
},
}
]
}
};
解决方案
尝试
{
test: /\.js$/,
use: 'babel-loader'
exclude: /node_modules\/(?!(specific_package_name1|specific_package_name2)).*/
}
在babel 转译时,将 etc替换specific_package_name1
为您不想被排除在外的包的名称。node_modules
请参阅此正则表达式以了解它如何与包名称匹配。
推荐阅读
- solr - 如何使SMUI上的数据存储持久化?
- javascript - 如何每次将一个添加到随机数组中?
- asp.net-mvc - 如何在 .NET 5 中反序列化枚举和数组
- ios - 如何将本地视频添加到 UIImageView 或 UIView 并使其循环播放?
- database - 预订到期的购物车
- swift - 自定义后退按钮目的地 SwiftUI
- javascript - 为什么我不能在本地主机上运行 server.js?
- ruby-on-rails - ActionController::RoutingError (没有路由匹配 [GET] "/packs/js/application...js")
- kubernetes - 持久卷和持久卷声明之间有什么关系(1:1 或 1:n)
- lua - 如何在pandoc中自动在标题之前添加分页符