[英]How to include a few node_modules package in babel-node
我試圖包括@ mycompany / package1和@ mycompany / package2,以及使用babel-node
進行其余代碼的編譯。 由於package1和package2在ES6中。 (還請注意,我沒有使用Webpack)
在我的jest
配置中,我將以下選項添加到了我的jest配置中,效果很好。 測試代碼時,將正確編譯軟件包
"transformIgnorePatterns": [
"/node_modules/(?!(@mycompany)/).*/"
],
但是,當嘗試運行babel-node時,我得到了錯誤。 在我的babel.config.js中
module.exports = {
presets: [
'@babel/preset-flow',
[
'@babel/preset-env',
{
targets: {
node: 8
}
}
]
],
plugins: ['@babel/plugin-proposal-class-properties']
};
我嘗試將以下代碼添加到babel.config.js中,但仍然抱怨node_modules / @ mycompany / package1中的ES6錯誤
我嘗試include
viz軟件包,但babel不會編譯我的src文件
include: [path.resolve(__dirname, 'node_modules/@mycompany/package1')]
include: ['/node_modules/((@mycompany)/).*/']
我嘗試exclude
@mycompany軟件包以外的所有內容,但在package1中仍然出現可移植錯誤
exclude: [/node_modules\\/(?!(@mycompany)\\/).*/],
我嘗試過玩無視,但基於閱讀文檔,這些似乎不是正確的選擇
我發現我們可以使用webpack
來做到這一點,以幫助將軟件包與您的其余代碼捆綁在一起。
這是我的NodeJS的webpack文件。
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const nodeEnv = process.env.NODE_ENV;
const isProduction = nodeEnv === 'production';
const compiler = webpack({
entry: ['@babel/polyfill', './src/server.js'],
output: {
path: path.resolve(__dirname, 'lib'),
filename: 'server.bundle.js',
libraryTarget: 'commonjs2'
},
externals: [
nodeExternals({
whitelist: [/@mycompany\/.*/]
})
],
plugins: plugins,
target: 'node',
mode: 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules\/(?!(@mycompany)\/).*/,
use: {
loader: 'babel-loader',
options: {
configFile: './babel.config.js'
}
}
}
]
}
});
if (isProduction) {
compiler.run((err, stats) => {
if (err) {
console.error(err);
return;
}
console.log(
stats.toString({
colors: true
})
);
});
} else {
let serverControl;
compiler.watch(
{
aggregateTimeout: 300,
poll: 1000
},
(err, stats) => {
if (serverControl) {
serverControl.kill();
}
if (err) {
console.error(err);
return;
}
console.log(
stats.toString({
colors: true
})
);
// change app.js to the relative path to the bundle created by webpack, if necessary
serverControl = spawn('node', [
path.resolve(__dirname, 'lib/server.bundle.js')
]);
serverControl.stdout.on('data', data => console.log(data.toString()));
serverControl.stderr.on('data', data => console.error(data.toString()));
}
);
}
注意最重要的部分是
- 添加
webpack-node-externals
。 由於這是一個node.js
服務器,因此我們不需要捆綁node_modules。- 確保將需要編譯/捆綁的軟件包列入
whitelist
,並確保包含要打包在babel-loader
軟件包
nodeExternal
告訴webpack
知道不捆綁任何node_modules。 whitelist
是說我們應該捆綁我們列出的軟件包
externals: [ nodeExternals({ whitelist: [/@mycompany\\/.*/] }) ]
該行表示排除@ mycompany / *包以外的所有node_modules
exclude: /node_modules\\/(?!(@mycompany)\\/).*/,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.