Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在ES6+;的webpack中的node_模块上使用babel loader;?_Reactjs_Webpack_Babeljs - Fatal编程技术网

Reactjs 如何在ES6+;的webpack中的node_模块上使用babel loader;?

Reactjs 如何在ES6+;的webpack中的node_模块上使用babel loader;?,reactjs,webpack,babeljs,Reactjs,Webpack,Babeljs,我有一个react项目,所有扩展都是.js,没有一个使用.jsx。我下载了一个新的库,它使用.jsx。在我的网页包中,加载程序作为异常运行在所有node_模块上。如何设置它,使其在node_模块中的.jsx文件上运行。当我试图用webpack运行我的产品构建时,我经常会遇到一个错误。说这个文件可能需要一个加载器,这是当构建遇到组件类中静态propTypes的ecma标准时。任何帮助都将不胜感激 class PDF extends Component { static propTypes =

我有一个react项目,所有扩展都是.js,没有一个使用.jsx。我下载了一个新的库,它使用.jsx。在我的网页包中,加载程序作为异常运行在所有node_模块上。如何设置它,使其在node_模块中的.jsx文件上运行。当我试图用webpack运行我的产品构建时,我经常会遇到一个错误。说这个文件可能需要一个加载器,这是当构建遇到组件类中静态propTypes的ecma标准时。任何帮助都将不胜感激

class PDF extends Component {
  static propTypes = {
    x: propType.String
  }
}

这就是你的网页配置的样子。这包含了所有的装载机 ES6与React redux Sass和其他实用程序

/* eslint-env node */
const autoprefixer = require('autoprefixer');
const CompressionPlugin = require('compression-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const SystemBellPlugin = require('system-bell-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

const highlightjsLanguages=['javascript', 'python', 'bash', 'java', 'cpp'];

const env=process.env.NODE_ENV;
const isProd = (env.toLowerCase().trim() === 'production')? true: false;
const vendor = [
      'react',
      'react-dom',
      'react-router-dom',
      'prop-types',
      'redux',
      'react-redux',
      'redux-thunk',
      'axios',
      'babel-polyfill',
      'browser-detect'
      ];
// Configuration object
const config = {
  devtool: isProd ? 'source-map' : 'source-map',
  entry: ['babel-polyfill','./src/index'],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: isProd ? '[name].[chunkhash].js' : 'bundle.js',
    publicPath: '/',
  },
  resolve: {
    extensions: ['*', '.js', '.jsx', '.json'],
  },
  target: 'web',
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.(css|scss|sass)$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [{
            loader: 'css-loader',
            options: {
              sourceMap: true,
            },
          }, {
            loader: 'postcss-loader',
            options: {
              sourceMap: true,
              plugins() {
                return [autoprefixer('last 2 versions', 'ie 10')];
              },
            },
          }, {
            loader: 'sass-loader',
            options: { sourceMap: true },
          }],
        }),
      },
      { test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?name=assests/fonts/[name].[ext]' },
      { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader?mimetype=application/font-woff&name=assests/fonts/[name].[ext]' },
      { test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?mimetype=application/octet-stream&name=assests/fonts/[name].[ext]' },
      { test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml&name=assests/fonts/[name].[ext]' },
      { test: /\.(jpe?g|png|gif|ico)$/i, loader: 'file-loader?name=assests/images/[name].[ext]' },
    ],
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    compress: true,
    port: 8000,
    historyApiFallback: true,
    hot: true
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new ExtractTextPlugin({
      filename: '[name].[contenthash].css',
      disable: !isProd,
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
    new SystemBellPlugin(),
    new CopyWebpackPlugin( [{from:'src/web.config',to:'./'}]),
    new webpack.ContextReplacementPlugin(
      /highlight\.js\/lib\/languages$/,
      new RegExp(`^./(${highlightjsLanguages.join('|')})$`)
    )
  ],
};

if (isProd) {
  Array.prototype.push.apply(config.plugins, [
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        warnings: false, // Suppress uglification warnings
        pure_getters: true,
        unsafe: true,
        unsafe_comps: true,
        screw_ie8: true
      },
      output: {
        comments: false,
      },
      exclude: [/\.min\.js$/gi] // skip pre-minified libs
      }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendors',
      minChunks(module) {
        const { context } = module;
        if (typeof context !== 'string') {
          return false;
        }
        return context.indexOf('node_modules') !== -1;
      },
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common',
      minChunks(module, count) {
        return count >= 2;
      },
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'runtime'
    }),
    new CompressionPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.(js|html)$/,
      threshold: 10240,
      minRatio: 0.8,
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
      noInfo: true,
      options: {
        context: './',
      },
    }),
    new HtmlWebpackPlugin({
      title: 'KM Q&A',
      filename: 'index.html',
      template: './src/index.ejs',
      favicon: './src/favicon.ico',
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
      inject: true,
    }),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.HashedModuleIdsPlugin()
  ]);
} else {
  config.entry.splice(1, 0, 'react-hot-loader/patch');
  Array.prototype.push.apply(config.plugins, [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      title: 'KM Q&A',
      filename: 'index.html',
      template: './src/index.ejs',
      inject: true,
      favicon: './src/favicon.ico',
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: false,
      debug: true,
      noInfo: false,
      options: {
        context: './',
      },
    }),
  ]);
}


module.exports = config;
这应该是你的.babelrc文件

{
  "presets": [
    [
      "env",
      { "modules": false }],
    "react"
    ],
    "plugins": [
      "react-hot-loader/babel",
      "transform-object-rest-spread",
      "transform-class-properties"
    ],
  "env":{
    "test":{
      "presets": [
        "env",
        "react"
    ],
    "plugins": [
      "transform-object-rest-spread",
      "transform-class-properties"
    ]}
  }
}
下面是带有Jest测试的basic packages.json

{
  "name": "react-starter",
  "version": "1.0.0",
  "main": "index.jsx",
  "scripts": {
    "start": "set NODE_ENV=development&& npm-run-all --parallel open:dev lint:watch npm:lock",
    "prebuild": "npm run remove-dist && mkdir dist",
    "build:prod": "set NODE_ENV=production&& webpack",
    "build:dev": "set NODE_ENV=development&& webpack",
    "lint": " esw src --color",
    "lint:watch": "npm run lint --watch",
    "open:dev": "webpack-dev-server",
    "open:dist": "http-server ./dist -p 8081 -s -o",
    "remove-dist": "rimraf ./dist",
    "npm:lock": "npm shrinkwrap",
    "test:dev": "set NODE_ENV=test&&Set TEST_ENV=development&&jest -u",
    "test:prod": "set NODE_ENV=test&&Set TEST_ENV=production&&jest -u",
    "coverage:dev": "set NODE_ENV=test&&Set TEST_ENV=development&&jest --coverage",
    "coverage:prod": "set NODE_ENV=test&&Set TEST_ENV=production&&",
    "installmodules": "npm install",
  },
  "license": "MIT",
  "dependencies": {
    "axios": "^0.17.1",
    "babel-polyfill": "^6.26.0",
    "detect-browser": "^2.0.0",
    "font-awesome": "^4.7.0",
    "prop-types": "^15.6.0",
    "raf": "^3.4.0",
    "react": "^16.1.1",
    "react-dom": "^16.1.1",
    "react-hot-loader": "^3.1.3",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.6",
    "axios-mock-adapter": "^1.10.0",
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.0.1",
    "babel-jest": "^21.2.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "compression-webpack-plugin": "^1.0.1",
    "copy-webpack-plugin": "^4.2.0",
    "css-loader": "^0.28.7",
    "enzyme": "^3.2.0",
    "enzyme-adapter-react-16": "^1.1.0",
    "eslint": "^4.10.0",
    "eslint-config-airbnb": "^16.1.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-jsx-a11y": "^6.0.2",
    "eslint-plugin-react": "^7.4.0",
    "eslint-watch": "^3.1.3",
    "extract-text-webpack-plugin": "^3.0.1",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.30.1",
    "http-server": "^0.10.0",
    "jest": "^21.2.1",
    "node-sass": "^4.6.1",
    "npm-run-all": "^4.1.1",
    "postcss-loader": "^2.0.8",
    "react-addons-perf": "^15.4.2",
    "react-test-renderer": "^16.1.1",
    "redux-mock-store": "^1.3.0",
    "sass-loader": "^6.0.6",
    "sinon": "^4.1.2",
    "style-loader": "^0.19.0",
    "system-bell-webpack-plugin": "^1.0.0",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4"
  },
  "optionalDependencies": {
    "bufferutil": "^3.0.3"
  },
  "jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "automock": false,
    "transform": {
      "^.+\\.jsx?$": "<rootDir>/node_modules/babel-jest",
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react/",
      "<rootDir>/node_modules/react-dom/"
    ],
    "transformIgnorePatterns": [
      "/node_modules/"
    ],
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ],
    "modulePathIgnorePatterns": [
      "/node_modules/"
    ],
    "collectCoverage": true,
    "coverageReporters": [
      "json",
      "lcov",
      "text"
    ]
  }
}
{
“名称”:“反应启动器”,
“版本”:“1.0.0”,
“main”:“index.jsx”,
“脚本”:{
“开始”:“set NODE_ENV=development&&npm run all--parallel open:dev lint:watch npm:lock”,
“预构建”:“npm运行删除dist&&mkdir dist”,
“build:prod”:“set NODE\u ENV=production&&webpack”,
“构建:开发”:“设置节点\环境=开发和网页包”,
“lint”:“esw src——颜色”,
“lint:watch”:“npm run lint--watch”,
“打开:开发”:“网页包开发服务器”,
“open:dist”:“http服务器/dist-p8081-s-o”,
“移除区域”:“rimraf./dist”,
“npm:锁定”:“npm收缩包装”,
“test:dev”:“set NODE\u ENV=test&&set test\u ENV=development&&jest-u”,
“test:prod”:“set NODE\u ENV=test&&set test\u ENV=production&&jest-u”,
“coverage:dev”:“set NODE\u ENV=test&&set test\u ENV=development&&jest--coverage”,
“覆盖率:产品”:“设置节点环境=测试和设置测试环境=生产和测试”,
“installmodules”:“npm安装”,
},
“许可证”:“麻省理工学院”,
“依赖项”:{
“axios”:“^0.17.1”,
“巴别塔polyfill”:“^6.26.0”,
“检测浏览器”:“^2.0.0”,
“字体真棒”:“^4.7.0”,
“道具类型”:“^15.6.0”,
“raf”:“^3.4.0”,
“反应”:“^16.1.1”,
“react dom”:“^16.1.1”,
“反应热加载程序”:“^3.1.3”,
“react redux”:“^5.0.6”,
“反应路由器dom”:“^4.2.2”,
“redux”:“^3.7.2”,
“redux thunk”:“^2.2.0”
},
“依赖性”:{
“自动刷新器”:“^7.1.6”,
“axios模拟适配器”:“^1.10.0”,
“巴别塔核心”:“^6.26.0”,
“babel eslint”:“^8.0.1”,
“巴别塔笑话”:“^21.2.0”,
“巴别塔加载器”:“^7.1.2”,
“babel插件转换类属性”:“^6.24.1”,
“巴别塔插件转换对象静止排列”:“^6.26.0”,
“巴别塔预设环境”:“^1.6.1”,
“巴别塔预设反应”:“^6.24.1”,
“压缩网页包插件”:“^1.0.1”,
“复制网页包插件”:“^4.2.0”,
“css加载器”:“^0.28.7”,
“酶”:“^3.2.0”,
“酶-适配器-反应-16”:“^1.1.0”,
“eslint”:“^4.10.0”,
“eslint配置airbnb”:“^16.1.0”,
“eslint加载程序”:“^1.9.0”,
“eslint插件导入”:“^2.8.0”,
“eslint-plugin-jsx-a11y”:“^6.0.2”,
“eslint插件反应”:“^7.4.0”,
“eslint手表”:“^3.1.3”,
“提取文本网页包插件”:“^3.0.1”,
“文件加载器”:“^1.1.5”,
“html网页包插件”:“^2.30.1”,
“http服务器”:“^0.10.0”,
“笑话”:“^21.2.1”,
“节点sass”:“^4.6.1”,
“npm全部运行”:“^4.1.1”,
“邮政编码加载器”:“^2.0.8”,
“react插件性能”:“^15.4.2”,
“反应测试渲染器”:“^16.1.1”,
“redux模拟商店”:“^1.3.0”,
“sass加载程序”:“^6.0.6”,
“信农”:“^4.1.2”,
“样式加载器”:“^0.19.0”,
“system bell网页包插件”:“^1.0.0”,
“网页包”:“^3.8.1”,
网页包开发服务器“^2.9.4”
},
“可选依赖项”:{
“bufferutil”:“^3.0.3”
},
“笑话”:{
“moduleNameMapper”:{
“\ \(jpg | jpeg | png | gif | eot | otf | webp | svg | ttf | woff | woff2 | mp4 | webm | wav | mp3 | m4a | aac | oga |)$”:“/(uu mocks |/uu/fileMock.js,
“\\(css | scss)$”:“/\uu mocks\uuu/styleMock.js”
},
“自动模拟”:错误,
“转变”:{
“^.+\.jsx?$”:“/node\u modules/babel jest”,
“\ \(jpg | jpeg | png | gif | eot | otf | webp | svg | ttf | woff | woff2 | mp4 | webm | wav | mp3 | m4a | aac | oga |)$”:“/\uu mocks |/uu/fileMock.js
},
“moduleFileExtensions”:[
“js”,
“jsx”
],
“模块目录”:[
“节点_模块”
],
“unmockedModulePathPatterns”:[
“/node_modules/react/”,
“/node_modules/react dom/”
],
“transformIgnorePatterns”:[
“/node_modules/”
],
“coveragePathIgnorePatterns”:[
“/node_modules/”
],
“modulePathIgnorePatterns”:[
“/node_modules/”
],
“覆盖范围”:正确,
“搬运工”:[
“json”,
“lcov”,
“文本”
]
}
}

是的,错误是正确的,您需要一个加载程序来解析ES6。要实现这一点,您需要安装并引用一个babel加载程序,最好是一个babel加载程序,它将把您的
jsx
文件所使用的所有奇特语法转换为大多数浏览器都能理解的语法(ES5)

如何在ES6+网页包中的节点_模块上使用babel loader

根据,您可以在终端中键入以下命令:

npm install babel-loader babel-core babel-preset-env
你会有

巴别塔装载机7.x |巴别塔6.x

安装在您的项目中

然后在webpack配置对象中,需要将
babel loader
添加到模块列表中,如下所示:

module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env']
        }
      }
    }
  ]

这就是如何在webpack for ES6中的node_模块上使用babel loader的方法。

如果我排除node_模块,我如何使它在包含在node_模块内的库上工作?排除
node_模块
仅适用于捆绑阶段,也就是说,babel不会尝试解析node_模块,但它们仍然会,被包括在最后的捆绑包中,未解析。谢谢,是的,在我的开发环境中,它工作得很好,但是为生产构建网页包不起作用。而那些节点_模块需要ES7传输,因为其中一个正在使用该语法。这是哪个模块?react pdf js infinite。在项目中无法将其传输。