我使用webpack4 + babel7。在我的JS脚本中,我需要导入NPM模块。该模块使用ES6类和模块。并且在构建捆绑软件之后,此类不会转换为标准功能。如何完全编译所需的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');
}
}
webpack.config.js中的测试失败
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules\/(?!@betakiller\/wamp-wrappe).*/
}
]
}
我的解决方案
.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
}
]
]
},
}
]
}
};
感谢您的帮助。
答案 0 :(得分:1)
尝试
{
test: /\.js$/,
use: 'babel-loader'
exclude: /node_modules\/(?!(specific_package_name1|specific_package_name2)).*/
}
在将specific_package_name1
等替换为要打包babel时不希望被排除在node_modules
中的软件包名称的地方。请参见this regex,以了解其与程序包名称的匹配方式。
答案 1 :(得分:0)
@axm__对我不起作用,但这似乎是正确的。这是Webpack 4.43。+和Babel 7.10。+对我有用的方式:
{{1}}
在检查文档时,我看到exclude属性可以作为另一条规则工作,我尝试了一下并且工作正常。也许对某人有用。
注意:我使用“ path.resolve”,但这不是必需的,因为我将Webpack放在另一个文件夹中,所以使用它。