gpt4 book ai didi

javascript - 禁用 Babel 中忽略的目录 "node_modules"

转载 作者:行者123 更新时间:2023-12-01 01:35:37 31 4
gpt4 key购买 nike

我使用 webpack4 + babel7。在我的 JS 脚本中,我需要导入 NPM 模块。该模块使用 ES6 类和模块。并且在构建 bundle 后,此类不会转换为标准函数。如何让我需要的NPM模块完全转译?

package.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
}
]
]
}

app.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);

ImportedClass.js

'use strict';

export default class ImportedClass {
action(){
console.log('ImportedClass');
}
}

NPM module result

Test imported class result

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 转译时,将 specific_package_name1 等替换为您不希望在 node_modules 中排除的包的名称。请参阅this regex查看它如何与包名称匹配。

关于javascript - 禁用 Babel 中忽略的目录 "node_modules",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858944/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com